Java httpClient连接池支持多线程高并发的实现
当采用HttpClient httpClient = HttpClients.createDefault() 实例化的时候。会导致Address already in use的异常。
信息: I/O exception (java.net.BindException) caught when processing request to {}->http:/ private static CloseableHttpClient getCloseableHttpClient() { CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(poolConnManager) .setRetryHandler(httpRequestRetryHandler) .build(); return httpClient; } private static Map<String, Object> buildResultMap(CloseableHttpResponse response, HttpEntity entity) throws IOException { Map<String, Object> result; result = new HashMap<>(2); result.put(KEY_STATUS_CODE, response.getStatusLine().getStatusCode()); //status code if (entity != null) { result.put(KEY_CONTENT, EntityUtils.toString(entity, "UTF-8")); //message content } return result; } public static Map<String, Object> postJson(String url, String message) { Map<String, Object> result = null; CloseableHttpClient httpClient = getCloseableHttpClient(); HttpPost httpPost = new HttpPost(url); CloseableHttpResponse response = null; try { httpPost.setHeader("Accept", "application/json;charset=UTF-8"); httpPost.setHeader("Content-Type", "application/json"); StringEntity stringEntity = new StringEntity(message); stringEntity.setContentType("application/json;charset=UTF-8"); httpPost.setEntity(stringEntity); response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); result = buildResultMap(response, entity); } catch (Exception e) { e.printStackTrace(); } finally { if (response != null) { try { EntityUtils.consume(response.getEntity()); response.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } }
到此这篇关于Java httpClient连接池支持多线程高并发的实现的文章就介绍到这了,更多相关Java httpClient连接池多线程高并发内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!