1、引入相关依赖包
jar包下载:httpcore4.5.5.jar fastjson-1.2.47.jar
通过post方式 传递Map
/**
* 通过post方式调用http接口
* @param url url路径
* @param map json格式的参数
* @param reSend 重发次数
* @return
* @throws Exception
*/
public static String sendPostByForm(String url, Map<String,String> map,int reSend) {
// CloseableHttpResponse response = null;
//声明返回结果
String result = "";
//开始请求API接口时间
long startTime=System.currentTimeMillis();
//请求API接口的响应时间
long endTime= 0L;
HttpEntity httpEntity = null;
UrlEncodedFormEntity entity = null;
HttpResponse httpResponse = null;
HttpClient httpClient = null;
try {
/**
* 创建一个httpclient对象
*/
httpClient = HttpClients.createDefault();
/**
* 创建一个post对象
*/
HttpPost httpPost = new HttpPost(url);
//设置参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String,String> elem = (Map.Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
}
entity = new UrlEncodedFormEntity(list,"utf-8");
httpPost.setEntity(entity);
LOGGER.info("请求{}接口的参数为{}",url,map);
//执行发送,获取相应结果
httpResponse = httpClient.execute(httpPost);
httpEntity= httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);
} catch (Exception e) {
LOGGER.error("请求{}接口出现异常",url,e);
if (reSend > 0) {
// LOGGER.info("请求{}出现异常:{},进行重发。进行第{}次重发",url,e.getMessage(),(HttpConstant.REQ_TIMES-reSend +1));
result = sendPostByForm(url, map, reSend - 1);
if (result != null && !"".equals(result)) {
return result;
}
}
}finally {
try {
EntityUtils.consume(httpEntity);
} catch (IOException e) {
LOGGER.error("http请求释放资源异常",e);
}
}
//请求接口的响应时间
endTime=System.currentTimeMillis();
LOGGER.info("请求{}接口的响应报文内容为{},本次请求API接口的响应时间为:{}毫秒",url,result,(endTime-startTime));
return result;
}