HttpClient請求URL
阿新 • • 發佈:2018-11-26
1. 編寫HttpClientUtil做POST和GET請求
import com.alibaba.fastjson.JSON; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URLEncoder; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Created by alibaba on 2017/11/8. */ public class HttpClientUtil { private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class); /** * @param url 請求地址 * @param param 請求引數 * * @return map - status 返回狀態 1-失敗 0-成功 Integer * @return map - result 失敗原因 or 請求成功後api的返回資訊 String * */ public static HashMap<String, Object> doPost(String url, Map<String,Object> param){ logger.info("url: " + url); String result = ""; Integer status = 0; HashMap<String,Object> returnMap = new HashMap<String,Object>(); try { HttpClient client = HttpClients.createDefault(); HttpPost request = new HttpPost(url); String jsonStr = ""; if(param != null) { jsonStr = JSON.toJSONString(param); } logger.info("jsonStr: " + jsonStr); StringEntity requestEntity = new StringEntity(jsonStr, "UTF-8"); requestEntity.setContentType("application/json;charset=UTF-8"); request.setEntity(requestEntity); HttpResponse response = client.execute(request); if(HttpStatus.SC_OK == response.getStatusLine().getStatusCode()){ HttpEntity responseEntity = response.getEntity(); if(responseEntity != null){ status = 0; result = EntityUtils.toString(responseEntity,"UTF-8"); }else{ status = 1; result = "POST介面響應實體為空!"; } }else{ status = 1; result = "POST介面請求出錯!"; } } catch (Exception e) { e.printStackTrace(); status = 1; result = "POST介面調用出現異常,exception: " + e.toString(); } if(status == 1){ logger.error("POST介面【" + url +"】請求出錯! 出錯資訊為: " + result); } returnMap.put("status", status); returnMap.put("result", result); return returnMap; } /** * @param url 請求地址 * @param param 請求引數 * * @return map - status 返回狀態 1-失敗 0-成功 Integer * @return map - result 失敗原因 or 請求成功後api的返回資訊 String * */ public static HashMap<String, Object> doGet(String url, Map<String,Object> param){ logger.info("Get url: " + url); String result = ""; Integer status = 0; HashMap<String,Object> returnMap = new HashMap<String,Object>(); try { HttpClient client = HttpClients.createDefault(); String paramStr = ""; if (param != null) { StringBuilder myStringBuilder = new StringBuilder("?"); Iterator<Map.Entry<String, Object>> it = param.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> entry = it.next(); Object key = entry.getKey(); myStringBuilder.append(key); myStringBuilder.append('='); String value = entry.getValue().toString(); myStringBuilder.append(URLEncoder.encode(value, "UTF-8")); if (it.hasNext()) { myStringBuilder.append("&"); } } paramStr = myStringBuilder.toString(); } String newUrl = url + paramStr; logger.info("GET url : " + newUrl); HttpGet request = new HttpGet(newUrl); HttpResponse response = client.execute(request); if(HttpStatus.SC_OK == response.getStatusLine().getStatusCode()){ HttpEntity responseEntity = response.getEntity(); if(responseEntity != null){ status = 0; result = EntityUtils.toString(responseEntity,"UTF-8"); }else{ status = 1; result = "GET介面響應實體為空!"; } }else{ status = 1; result = "GET介面請求出錯!"; } } catch (Exception e) { e.printStackTrace(); status = 1; result = "GET介面調用出現異常,exception: " + e.toString(); } if(status == 1){ logger.error( "GET介面【" + url +"】請求出錯! 出錯資訊為: " + result); } returnMap.put("status", status); returnMap.put("result", result); return returnMap; } /* public static void main(String[] args) { //測試doget String url = "http://XX.XX.XX.XX"; HashMap<String, Object> param = new HashMap<String, Object>(); param.put("from", 1510120000); param.put("to", 1510128912); HashMap<String, Object> returnMap = HttpClientUtil.doGet(url, param); Integer status = (Integer)returnMap.get("status"); String result = (String)returnMap.get("result"); logger.info("doGet status: " + status); logger.info("doGet result: " + result); //測試dopost // String url = "http://XXX.XX.XX.XX/api"; // HashMap<String, Object> param = new HashMap<String, Object>(); // param.put("key", "XXXX-XXXX-XXX-XXXX-XXXX"); // param.put("user","test"); // param.put("method", "testMethod"); // // HashMap<String, Object> returnMap = HttpClientUtil.doPost(url, param); // // Integer status = (Integer)returnMap.get("status"); // String result = (String)returnMap.get("result"); // // logger.info("doPost status: " + status); // logger.info("doPost result: " + result); }*/ }
2. 呼叫doPost或doGet方法請求URL
/** * 請求url * @param param 對接欄位封裝物件 * @return map - status 返回狀態 1-失敗 0-成功 Integer * @return map - result 失敗原因 * */ public static HashMap<String, Object> dispatchUrl(Object param) { // TODO Auto-generated method stub String url = Constants.API_URL; //請求引數 Map<String,Object> param = new HashMap<String,Object>(); param.put("key", "XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX"); param.put("user","test"); param.put("method", "testMethod"); param.put("data", param); logger.info("JSON.toJSONString(param): " + JSON.toJSONString(param)); HashMap<String,Object> returnMap = new HashMap<String, Object>(); //處理返回結果 returnMap = HttpClientUtil.doPost(url, param, "UTF-8"); String responseResult = (String)returnMap.get("result"); Integer status = (Integer)returnMap.get("status"); logger.info("status: " + status + "; responseResult: " + responseResult); if(status.equals(1)){//後臺出錯 請求出錯 return returnMap; } Integer statusCode = 0; JSONObject obj = JSONObject.parseObject(responseResult); statusCode = (Integer)obj.get("statusCode"); //狀態碼為失敗 if(statusCode == null || statusCode.equals(1)){ returnMap.put("status", 1); returnMap.put("result", (String)obj.get("errorMessage")); return returnMap; } //無responseData //String dataStr = obj.get("responseData").toString(); return returnMap; } public static String convertStreamToString(InputStream is) throws UnsupportedEncodingException { StringBuilder sb1 = new StringBuilder(); byte[] bytes = new byte[4096]; int size = 0; try { while ((size = is.read(bytes)) > 0) { String str = new String(bytes, 0, size, "UTF-8"); sb1.append(str); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb1.toString(); }