这是一个创建于 852 天前的主题,其中的信息可能已经有所发展或是发生改变。
public static String post(String url, Map<String, String> paramMap, String charset) {
CloseableHttpClient httpClient = PoolingHttpClientFactory.getInstance().createHttpClient(); //创建实例对象
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
try {
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Iterator<Map.Entry<String, String>> it = paramMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps, charset));
// //设置连接 /读取超时时间
// RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000).build();//设置请求和传输超时时间
// httpPost.setConfig(requestConfig);
response = httpClient.execute( httpPost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
// String result = EntityUtils.toString(entity);
// EntityUtils.consume(entity);
return result;
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (null != response) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
return null;
}
这是原代码,在在 finally 下面加上这几个会不会好点,因为线上环境进程线程假死或者直接返回 Http Request Invalid 不知道是不是这个方法写的有问题还是请求的服务器抗不住并发
if( httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (null != response) {
try {
httpPost.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}