想请教一下各位 V 友这 http 请求问题

2022-07-30 02:35:49 +08:00
 amrl
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);
}
}
744 次点击
所在节点    问与答
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/869582

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX