您的位置:首页 > 理论基础 > 计算机网络

发送https请求时绕过证书验证

2018-07-05 19:04 1216 查看
package com.example.demo.http;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;

import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;

/**
* 获取https访问权限
*
* @author LVXY 2016年11月18日 上午11:51:15
* @version V2.0
*
*/
public abstract class SSLUtils {
private static final int MAXTOTAL = 500;//默认最大连接数
private static final int DEFAULTMAXPERROUTE = 500;//默认每个主机的最大链接数
private static HttpRequestRetryHandler httpRequestRetryHandler = new DefaultHttpRequestRetryHandler();//默认不进行重试处理
private static CloseableHttpClient httpClient;

static {
//采用绕过验证的方式处理https请求
ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();

HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}

};
SSLContext sslContext = createIgnoreVerifySSL();

SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,hostnameVerifier);

Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", plainsf)
.register("https", sslsf)
.build();

PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(MAXTOTAL);// 设置最大连接数
cm.setDefaultMaxPerRoute(DEFAULTMAXPERROUTE);// 设置每个路由的默认连接数

//连接保持时间
ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
try {
return Long.parseLong(value) * 1000;
} catch (NumberFormatException ignore) {
}
}
}
return 30 * 1000;
}
};

httpClient = HttpClients.custom()
.setConnectionManager(cm)
.setRetryHandler(httpRequestRetryHandler)
.setKeepAliveStrategy(myStrategy)
.build();
}

public static CloseableHttpClient createSSLInsecureClient() {
try {
return httpClient;
} catch (Exception e) {
e.printStackTrace();
}
return  HttpClients.createDefault();
}

/**
* 请求重试处理
* 默认不进行任何重试
*/
private static class DefaultHttpRequestRetryHandler implements HttpRequestRetryHandler {
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
return false;
}
}

public static class IdleConnectionMonitorThread extends Thread {
private final PoolingHttpClientConnectionManager connMgr;

public IdleConnectionMonitorThread(PoolingHttpClientConnectionManager connMgr) {
super();
this.connMgr = connMgr;
}

@Override
public void run() {
while (true) {
try {
sleep(30000);
connMgr.closeExpiredConnections(); // 关闭过期的连接
connMgr.closeIdleConnections(30, TimeUnit.SECONDS); // 关闭空闲时间超过30秒的连接
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

/**
* 绕过验证
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static SSLContext createIgnoreVerifySSL() {
SSLContext sslContext = null;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException {//信任所有
return true;
}
}).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}

return sslContext;
}

//代码备份
/*    public static CloseableHttpClient createSSLInsecureClientBak() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException {//信任所有
return true;
}
}).build();
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,hostnameVerifier);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return  HttpClients.createDefault();
}*/
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HttpClient Apache Java