最近項目中壓測,利用httpclient訪問接口報錯蔼囊。錯誤信息如下:
錯誤原因分析:
并發(fā)調(diào)用同一個httpclient去請求數(shù)據(jù)導(dǎo)致焚志,當(dāng)上一個post|get請求尚未結(jié)束時,又啟新的線程再次使用該httpclient請求數(shù)據(jù)畏鼓。解決方案:
采用線程池酱酬,從線程池中獲取httpclient。
改用線程池中訪問https\http鏈接類型接口完整代碼云矫,使用方法:
- 工具類
public class HttpClientUtils {
private static CloseableHttpClient HTTPCLIENT;
private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
private static RequestConfig REQUESTCONFIG = RequestConfig.custom()
.setSocketTimeout(1000)
.setConnectTimeout(1000)
.setConnectionRequestTimeout(1000)
.build();
static PoolingHttpClientConnectionManager cm;
static {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
HTTPCLIENT = HttpClientBuilder.create().setRetryHandler((exception, executionCount, context) -> {
return false;
}).setDefaultRequestConfig(REQUESTCONFIG).setConnectionManager(cm).build();
}
public static String get(String url) throws IOException {
try {
HttpGet httpget = new HttpGet(url);
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(
final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
logger.error("請求{},出現(xiàn)了錯誤{}", url, status);
return "出錯了";
//throw new ClientProtocolException("Unexpected response status: " + status);
}
}
};
String responseBody = HTTPCLIENT.execute(httpget, responseHandler);
return responseBody;
} finally {
}
}
public static String post(String url,Map map) throws IOException {
String result = null;
HttpPost post = new HttpPost(url);
// System.out.println(map);
post.setHeader("content-type","application/json");
String param = JSON.toJSONString(map);
StringEntity entity = new StringEntity(param,"UTF-8");
post.setEntity(entity);
try {
HttpResponse response = HTTPCLIENT.execute(post);
result = EntityUtils.toString(response.getEntity(),"UTF-8");
// System.out.println(result);
return result;
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public static HttpResponse postResponse(String url,Map map) throws IOException {
String result = null;
HttpPost post = new HttpPost(url);
// System.out.println(map);
post.setHeader("content-type","application/json");
String param = JSON.toJSONString(map);
StringEntity entity = new StringEntity(param,"UTF-8");
post.setEntity(entity);
try {
HttpResponse response = HTTPCLIENT.execute(post);
System.out.println(response.getAllHeaders());
System.out.println(response.getEntity());
result = EntityUtils.toString(response.getEntity(),"UTF-8");
// System.out.println(result);
return response;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
- 調(diào)接口
HttpPost post = new HttpPost(url);
String result = HttpClientUtils.post(url, map);