http请求工具类--CloseableHttpClient的post请求

public static String doPost(String url, String encoding, Map<String, Object> params) {
String result = null;
CloseableHttpResponse httpResp = null;
CloseableHttpClient httpclient = null;
try {
int socketTimeout = 15000;
int connectTimeout = 15000;
SocketConfig socketConfig = SocketConfig.custom()
.setSoKeepAlive(false)
.setSoLinger(1)
.setSoReuseAddress(true)
.setSoTimeout(10000)
.setTcpNoDelay(true)
.build();
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(socketTimeout)
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectTimeout)
.build();
httpclient = HttpClientBuilder.create()
.setDefaultSocketConfig(socketConfig)
.setDefaultRequestConfig(config)
.build();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("accept", "/");
httpPost.setHeader("connection", "Keep-Alive");
httpPost.setHeader("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36");
if (params != null && params.size() > 0) {
List paramList = new ArrayList<>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
httpPost.setEntity(new UrlEncodedFormEntity(paramList, encoding));
}
long start = System.currentTimeMillis();
httpResp = httpclient.execute(httpPost);
long end = System.currentTimeMillis();
logger.info("end-start/s:{}", end - start);
if (httpResp.getEntity() != null) {
result = EntityUtils.toString(httpResp.getEntity(), encoding);
long end1 = System.currentTimeMillis();
logger.info("end1-end/s:{}", end1 - end);
EntityUtils.consume(httpResp.getEntity());
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
try {
if (httpResp != null)
httpResp.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
try {
if (httpclient != null)
httpclient.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
return result;
}

posted @ 2022-01-21 17:39  张豪轶  阅读(728)  评论(0)    收藏  举报