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; }