大家做项目的时候常常涉及到调用很多https的地址,有时候会出现这种错误,需要我们绕过验证,绕过验证后的工具类如下,大家可以直接使用
依赖如下
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.3</version>
</dependency>
package com.demo.util;
import com.demo.exce.WebException;
import com.google.common.base.Charsets;
import com.google.common.base.Stopwatch;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
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.entity.ContentType;
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.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.net.SocketTimeoutException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class HttpUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);
private static final int DEFAULT_TIMEOUT = 30000;
private static final RequestConfig DEFAULT_REQUEST_CONFIG = RequestConfig.custom()
.setSocketTimeout(DEFAULT_TIMEOUT)
.setConnectionRequestTimeout(DEFAULT_TIMEOUT)
.setConnectTimeout(DEFAULT_TIMEOUT).build();
static SSLContext sslcontext;
static {
try {
sslcontext = createIgnoreVerifySSL();
} catch (Exception e) {
e.printStackTrace();
}
}
// 设置协议http和https对应的处理socket链接工厂的对象
private static Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
private static PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
private static CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).setProxy(new HttpHost("localhost", 8888))
.setMaxConnTotal(1200)
.setMaxConnPerRoute(1200)
.setDefaultRequestConfig(DEFAULT_REQUEST_CONFIG)
.build();
private HttpUtils() {
}
/**
* 绕过验证
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSLv3");
// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sc.init(null, new TrustManager[] { trustManager }, null);
return sc;
}
public static String get(String url){
RequestBuilder requestBuilder = RequestBuilder.get(url);
requestBuilder.setConfig(DEFAULT_REQUEST_CONFIG);
try {
return doRequest(requestBuilder.build());
} catch (Exception e) {
LOGGER.error("HttpUtils get request error", e);
throw new WebException(e);
}
}
public static String get(String uri, Map<String, String> params) throws Exception {
RequestBuilder requestBuilder = RequestBuilder.get(uri);
requestBuilder.setConfig(DEFAULT_REQUEST_CONFIG);
for (Map.Entry<String, String> p : params.entrySet()) {
requestBuilder.addParameter(p.getKey(), p.getValue());
}
return doRequest(requestBuilder.build());
}
public static String getWithHeaders(String uri, Map<String, String> params) throws IllegalArgumentException,Exception {
RequestBuilder requestBuilder = RequestBuilder.get(uri);
requestBuilder.setConfig(DEFAULT_REQUEST_CONFIG);
for (Map.Entry<String, String> p : params.entrySet()) {
requestBuilder.addHeader(p.getKey(), p.getValue());
}
return doRequest(requestBuilder.build());
}
public static String post(String uri, Map<String, String> params) throws Exception {
RequestBuilder requestBuilder = RequestBuilder.post(uri);
if (params != null) {
for (Map.Entry<String, String> p : params.entrySet()) {
requestBuilder.addParameter(p.getKey(), p.getValue());
}
}
requestBuilder.setConfig(DEFAULT_REQUEST_CONFIG);
return doRequest(requestBuilder.build());
}
public static String post(String uri, Map<String, String> headers, Map<String, String> params) throws Exception {
RequestBuilder requestBuilder = RequestBuilder.post(uri);
for (Map.Entry<String, String> header : headers.entrySet()) {
requestBuilder.addHeader(header.getKey(), header.getValue());
}
for (Map.Entry<String, String> p : params.entrySet()) {
requestBuilder.addParameter(p.getKey(), p.getValue());
}
requestBuilder.setConfig(DEFAULT_REQUEST_CONFIG);
return doRequest(requestBuilder.build());
}
public static String postWithJson(String uri, String json) {
RequestBuilder bu = RequestBuilder.post(uri);
bu.setEntity(EntityBuilder.create().setContentType(ContentType.APPLICATION_JSON).setContentEncoding(Charsets.UTF_8.name()).setText(json).build());
bu.setConfig(DEFAULT_REQUEST_CONFIG);
try {
return doRequest(bu.build());
} catch (Exception e) {
LOGGER.error("HttpUtils postWithJson request error", e);
throw new WebException(e);
}
}
public static String postWithJsonAndHeaders(String uri, Map<String, String> headers, String json) {
RequestBuilder bu = RequestBuilder.post(uri);
for (Map.Entry<String, String> header : headers.entrySet()) {
bu.addHeader(header.getKey(), header.getValue());
}
bu.setEntity(EntityBuilder.create().setContentType(ContentType.APPLICATION_JSON).setContentEncoding(Charsets.UTF_8.name()).setText(json).build());
bu.setConfig(DEFAULT_REQUEST_CONFIG);
try {
return doRequest(bu.build());
} catch (Exception e) {
LOGGER.error("HttpUtils postWithJsonAndHeaders request error", e);
throw new WebException(e);
}
}
private static String doRequest(HttpUriRequest request) throws Exception {
Stopwatch stopwatch = Stopwatch.createStarted();
try {
return EntityUtils.toString(httpClient.execute(request).getEntity());
} catch (RuntimeException e) {
// 请求超时
LOGGER.error("HttpUtils postWithJson request connection timeout", e);
throw e;
} catch (SocketTimeoutException e) {
//服务接口响应超时
LOGGER.error("HttpUtils postWithJson request socket timeout", e);
throw new Exception(e);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
throw new Exception(e);
} finally {
Stopwatch finishWatch = stopwatch.stop();
Long seconds = finishWatch.elapsed(TimeUnit.MILLISECONDS);
LOGGER.info("http execute cost total seconds {}", seconds);
}
}
}