post请求接口工具类
直接上代码:
// 发送POST请求(url为接口地址,pushData是json字符串,该请求参数会传入在请求body中)
private static final String MEDIA_TYPE_FORM = "application/x-www-form-urlencoded";
public static String post(String url, String pushData) throws Exception {
log.info("=======数据参数=======:" + pushData);
String body = "";
//创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
//创建post方式请求对象
HttpPost httpPost = new HttpPost(path);
//装填参数
StringEntity s = new StringEntity(pushData, "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
MEDIA_TYPE_FORM));
//设置参数到请求对象中
httpPost.setEntity(s);
//设置header信息
httpPost.setHeader("Content-type", "application/json");
// httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
int status = response.getStatusLine().getStatusCode();
log.info("==调取接口返回状态码:" + status);
if (status >= HttpStatus.SC_MULTIPLE_CHOICES) {
body = "404" + EntityUtils.toString(entity, "utf-8");
} else {
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, "utf-8");
}
}
EntityUtils.consume(entity);
//释放链接
response.close();
return body;
}