import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
代码实现:
/**
* http发送POST请求
*
* @author J.M.C
* @since 2019年1月16日
* @param url 长连接URL
* @param paramsJson 请求参数body
* @return result 字符串
*/
public static String httpPostRequest(String url, JSONObject paramsJson) {
logger.info("httpPostRequest url : " + url + " paramMap : " + paramsJson);
if(StringUtil.isEmptyStr(url)){
logger.error("httpPostRequest url is null");
return null;
}
String result = "";
try {
// 创建httpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建httpPost远程连接实例
HttpPost httpPost = new HttpPost(url);
// 配置请求参数实例
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000)// 设置连接主机服务超时时间
.setConnectionRequestTimeout(10000)// 设置连接请求超时时间
.setSocketTimeout(30000)// 设置读取数据连接超时时间
.build();
// 为httpPost实例设置配置
httpPost.setConfig(requestConfig);
// 设置请求头
httpPost.addHeader("content-type", "application/json;charset=utf-8");
// 封装post请求参数
httpPost.setEntity(new StringEntity(paramsJson.toJSONString(), Charset.forName("UTF-8")));
// httpClient对象执行post请求,并返回响应参数对象
~~// HttpResponse httpResponse = httpClient.execute(httpPost);~~
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
// 从响应对象中获取响应内容
result = EntityUtils.toString(httpResponse.getEntity());
} catch (UnsupportedEncodingException e) {
logger.error("URLUtil.httpPostRequest encounters an UnsupportedEncodingException : {}",e);
} catch (IOException e) {
logger.error("URLUtil.httpPostRequest encounters an IOException : {}",e);
}
logger.info("URLUtil.httpPostRequest -----result----: " + result);
return result;
}
下面是http依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>