使用 PoolingHttpClientConnectionManager 鏈接池管理類 ...
public class HttpClientUtil { private static PoolingHttpClientConnectionManager connectionManager = null; private static IdleConnectionMonitorThread scan = null; private static int MAX_CONN_TOTAL = 1000; private static int MAX_CONN_PERROUTE = 600; public static HttpClientResponseEntity webRequestToServer(String requestUri, String method, byte[] requestData, final int timeOut, String encodeName, Map<String, String> headers) throws Exception { HttpClientResponseEntity responseEntity = new HttpClientResponseEntity(); CloseableHttpResponse response = null; InputStream inputStream = null; HttpUriRequest httpUriRequest = null; try { //設置協議http和https對應的處理socket鏈接工廠對象 SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", sslsf) .build(); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(timeOut) .setSocketTimeout(timeOut) .setConnectionRequestTimeout(timeOut) .build(); SocketConfig socketConfig = SocketConfig.custom() .setSoTimeout(timeOut) .build(); if (connectionManager == null) { connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); connectionManager.setMaxTotal(MAX_CONN_TOTAL); connectionManager.setDefaultMaxPerRoute(MAX_CONN_PERROUTE); } if (scan == null) { //清理無效的連接 scan = new IdleConnectionMonitorThread(connectionManager); scan.start(); } HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setConnectionManager(connectionManager); httpClientBuilder.setDefaultRequestConfig(requestConfig); httpClientBuilder.setDefaultSocketConfig(socketConfig); httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)); httpClientBuilder.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(HttpResponse response, HttpContext context) { final HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { final HeaderElement he = it.nextElement(); final String param = he.getName(); final String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { try { return Long.parseLong(value) * 1000; } catch (final NumberFormatException ignore) { } } } return timeOut; } }); CloseableHttpClient httpClient = httpClientBuilder.build(); switch (method) { case "POST": HttpPost httpPost = new HttpPost(requestUri); httpPost.setEntity(new ByteArrayEntity(requestData)); if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { httpPost.setHeader(entry.getKey(), entry.getValue()); } } httpUriRequest = httpPost; break; case "GET": HttpGet httpGet = new HttpGet(requestUri); if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { httpGet.setHeader(entry.getKey(), entry.getValue()); } } httpUriRequest = httpGet; break; default: throw new Exception("請求方式不存在!"); } response = httpClient.execute(httpUriRequest); inputStream = response.getEntity().getContent(); responseEntity.setResponseCode(String.valueOf(response.getStatusLine().getStatusCode())); if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); byte[] buff = new byte[1000]; int ri = 0; while ((ri = inputStream.read(buff, 0, 1000)) > 0) { swapStream.write(buff, 0, ri); } responseEntity.setResponseByteArray(swapStream.toByteArray()); responseEntity.setResponseBody(new String(responseEntity.getResponseByteArray(), encodeName)); } else { responseEntity.setResponseMsg(response.getStatusLine().getReasonPhrase()); } inputStream.close(); } catch (Exception e) { responseEntity.setResponseCode("-1"); responseEntity.setResponseMsg(e.getMessage()); if (e instanceof SocketTimeoutException) { responseEntity.setResponseCode("timeout"); responseEntity.setResponseMsg("介面超時(超時時間:" + timeOut + "毫秒)"); } } finally { if (httpUriRequest != null) { httpUriRequest.abort(); } if (response != null) { EntityUtils.consumeQuietly(response.getEntity()); } } return responseEntity; } }
使用 PoolingHttpClientConnectionManager 鏈接池管理類