Http調用第三方接口代碼:
/** * 房融界接口對接 * @return */ public Map<String,Object> frjRequest(){ String url="房融界提供的接口地址"; String result = ""; HttpPost httppost=new HttpPost(url); //建立HttpPost對象 CloseableHttpClient client = HttpClients.createDefault();//創建HttpClient對象 try { //添加參數 List<NameValuePair> paramsList=new ArrayList<NameValuePair>(); paramsList.add(new BasicNameValuePair("鍵","值")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramsList, "UTF-8"); //設置請求和傳輸時長 RequestConfig.Builder builder = RequestConfig.custom(); builder.setSocketTimeout(120000); builder.setConnectTimeout(60000); RequestConfig config = builder.build(); httppost.setEntity(entity); httppost.setConfig(config); //發送Post CloseableHttpResponse response = client.execute(httppost); HttpEntity httpEntity = response.getEntity(); if (httpEntity != null) { result = EntityUtils.toString(httpEntity, "UTF-8"); } } catch (IOException e) { e.printStackTrace(); } finally { try { client.close(); httppost.releaseConnection(); } catch (IOException e) { logger.info(e.toString(), e); } } return JSON.parseObject(result, Map.class); }
方法二:傳遞JSON格式請求
/** * 發送json流數據*/ public static String postWithJSON(String url, String jsonParam) throws Exception { HttpPost httpPost = new HttpPost(url); CloseableHttpClient client = HttpClients.createDefault(); String respContent = null; StringEntity entity = new StringEntity(jsonParam, "utf-8");//解決中文亂碼問題 entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); httpPost.setEntity(entity); HttpResponse resp = client.execute(httpPost); if (resp.getStatusLine().getStatusCode() == 200) { HttpEntity he = resp.getEntity(); respContent = EntityUtils.toString(he, "UTF-8"); } return respContent; }
注意:
//Map --> JSONString Map<String,Object> param = new HashMap<>(); param.put("name",name); param.put("phone",phone); String jsonParam = JSONUtils.toJSONString(param); //JSONString --> JSONObj JSONObject resultObj = JSONObject.parseObject(jsonParam);
方法三:傳遞字符串格式數據
public static String postWithString(String url, String stringParam) throws Exception { HttpPost httpPost = new HttpPost(url); CloseableHttpClient client = HttpClients.createDefault(); String respContent = null; StringEntity entity = new StringEntity(stringParam, "utf-8");//解決中文亂碼問題 entity.setContentEncoding("UTF-8"); entity.setContentType("text"); httpPost.setEntity(entity); HttpResponse resp = client.execute(httpPost); if (resp.getStatusLine().getStatusCode() == 200) { HttpEntity he = resp.getEntity(); respContent = EntityUtils.toString(he, "UTF-8"); } return respContent; }