赞
踩
httpclient工具类,线程安全的连接池和忽略ssl
import java.io.IOException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.ssl.SSLContexts; import org.apache.http.util.EntityUtils; public class HttpClientUtil { private static PoolingHttpClientConnectionManager cm = null; static { SSLContext sslContext = null; try { sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustManager[]{new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }}).build(); } catch (Exception e) { e.printStackTrace(); } SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory( sslContext, NoopHostnameVerifier.INSTANCE); cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(100); cm.setDefaultMaxPerRoute(20); } public static CloseableHttpClient getHttpClient() { RequestConfig config = RequestConfig.custom() .setConnectTimeout(5000) .setSocketTimeout(5000) .setConnectionRequestTimeout(5000) .build(); return HttpClientBuilder.create() .setConnectionManager(cm) .setDefaultRequestConfig(config) .setConnectionTimeToLive(60, TimeUnit.SECONDS) .setSSLSocketFactory(sslConnectionSocketFactory) .build(); } public static String doGet(String url) throws IOException { CloseableHttpClient httpClient = getHttpClient(); HttpGet httpGet = new HttpGet(url); CloseableHttpResponse httpResponse = httpClient.execute(httpGet); try { HttpEntity entity = httpResponse.getEntity(); return EntityUtils.toString(entity); } finally { httpResponse.close(); httpClient.close(); } } }
我们使用了Apache HttpClient的连接池机制,通过自定义连接管理器(PoolingHttpClientConnectionManager)来管理HTTP连接。连接管理器支持设置最大连接数(setMaxTotal)和每个路由的最大连接数(setDefaultMaxPerRoute)等参数,以优化连接池的效率。
为了忽略SSL证书,我们创建了一个自定义的SSLContext,并将其与NoopHostnameVerifier一起传递给SSLConnectionSocketFactory。这样,我们就可以在不进行SSL证书验证的情况下使用HTTPS连接
import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContexts; public class HttpUtil { private static final int MAX_TOTAL_CONNECTIONS = 1000; private static final int MAX_CONNECTIONS_PER_ROUTE = 100; private static final int SOCKET_TIMEOUT = 5000; private static final int CONNECTION_TIMEOUT = 3000; private static final int CONNECTION_REQUEST_TIMEOUT = 500; public static HttpClient createHttpClient(boolean ignoreSSL) throws Exception { HttpClientBuilder builder = HttpClientBuilder.create(); // 设置连接池 PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(MAX_TOTAL_CONNECTIONS); connectionManager.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE); builder.setConnectionManager(connectionManager); // 设置超时时间 RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(SOCKET_TIMEOUT) .setConnectTimeout(CONNECTION_TIMEOUT) .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT) .build(); builder.setDefaultRequestConfig(requestConfig); if (ignoreSSL) { // 忽略SSL证书验证 SSLContextBuilder sslContextBuilder = SSLContexts.custom(); sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); SSLContext sslContext = sslContextBuilder.build(); builder.setSSLContext(sslContext); builder.setSSLHostnameVerifier(new NoopHostnameVerifier()); } CloseableHttpClient httpClient = builder.build(); return httpClient; } public static void execute(HttpClient httpClient, HttpUriRequest request) throws Exception { httpClient.execute(request); } }
eg:
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
public class Main {
public static void main(String[] args) throws Exception {
HttpUriRequest request = new HttpGet("http://www.google.com");
HttpClient httpClient = HttpUtil.createHttpClient(true);
HttpUtil.execute(httpClient, request);
((CloseableHttpClient) httpClient).close();
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。