1. 程式人生 > >java通過http請求拿資料

java通過http請求拿資料

  我們通常做Java後臺介面,是讓前端訪問的,讓前端獲取資料或者做增刪改查,但是有時候,我們做的Java介面是用來接收其他語言程式(如:python)查詢到的結果,Java當中間件將其他http請求查詢到的json結果處理後傳給前端,本次做的處理只是記錄每次查詢時間,結果,查詢條件,沒有查到結果的請求給出友好提示,同時記錄.

	@Value("${abnormal.view}")
	private String url;


        private String getUrl() {
		return url;
	}

propreties檔案中新增
abnormal.view =http\://000.000.000.00\:8080/abnormal_view
package **.***.view.web;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springside.modules.mapper.JsonMapper;

import **.***.view.entity.Log;
import **.***.view.entity.Params;
import **.***.view.service.LogService;

import com.google.common.collect.Maps;

@RestController
@RequestMapping(value="json")
public class DataController {
	private final JsonMapper mapper = JsonMapper.nonDefaultMapper();
	
	@Autowired 
	private LogService logService;
	
	@RequestMapping(value="data",method = RequestMethod.POST)
	public String Json(@RequestBody Params params){
		Log data = this.getJson(params);
		Map<String,Object> result = Maps.newHashMap();
		result.put("data", data.getJson());
		//查不到資料時,python返回"{}\n"
		if(data.getJson().length()<=3){
			result.put("description","系統沒有查詢到資料,請修改查詢條件");
			result.put("status", "blank");
		}else{
			result.put("description","資料請求成功");
			result.put("status", "ok");
		}
		return mapper.toJson(result);
	}

    	public Log getJson(Params params) {
		String requestJson = mapper.toJson(params);
		Log log = new Log();
		long startTimeMillis = System.currentTimeMillis();
		String responseJson = HttpUtils.doPostRequest(requestJson, this.getUrl());
		long endTimeMillis = System.currentTimeMillis();
		log.setParams(requestJson);
		log.setJson(responseJson);
		log.setDate(getCurrentTime());
		log.setRequestTime(String.valueOf(endTimeMillis-startTimeMillis));
		//查不到資料時,python返回"{}\n"
		if(responseJson.length()<=3){
			log.setStatus("blank");
		}else{
			log.setStatus("ok");
		}
		logDao.save(log);
		return log;
	}


}
package **.***.view.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


public class HttpUtils {

	
	@SuppressWarnings({ "resource", "deprecation" })
    //requestJson:請求引數,url:呼叫properties檔案中的http請求
	public static String doPostRequest(String requestJson, String url) {
		HttpClient httpClient = null;
		HttpPost httpPost = null;
		String result = null;
		Map<String, String> params = new HashMap<String, String>();
		httpClient = new DefaultHttpClient();
		httpPost = new HttpPost(url);
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		
		//params.put("patient_id", requestJson);
		params.put("data", requestJson);
		Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, String> elem = (Entry<String, String>) iterator.next();
			list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
		}

		UrlEncodedFormEntity entity = null;

		try {
			entity = new UrlEncodedFormEntity(list, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		httpPost.setEntity(entity);
		HttpResponse response = null;
		try {
			response = httpClient.execute(httpPost);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (response != null) {
			HttpEntity resEntity = response.getEntity();
			try {
				result = EntityUtils.toString(resEntity, "utf-8");
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
}