针对不同的http客户端,有不同的配置方式,但总的来说,就是配置SSLSocketFactory和HostnameVerifier。
一、okhttp
可以参考:https://blog.csdn.net/u014752325/article/details/73185351
二、httpclient
这里又分为连接池和非连接池,配置稍有不同。
连接池:
public final CloseableHttpClient getCustomClient() {
try {
HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
(TrustStrategy) (X509Certificate[] arg0, String arg1) -> true).build();
builder.setSSLContext(sslContext);
HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
builder.setConnectionManager(connMgr);
return builder.build();
} catch (Exception ex) {
LOG.log(Level.SEVERE, ex.getMessage(), ex);
}
return getSystemClient();
}
非连接池:
CloseableHttpClient configureHttpClient(boolean enableSslVerify) {
HttpClientBuilder builder = HttpClientBuilder.create();
if (enableSslVerify) {
return builder.build();
}
SSLContext sslContext = null;
try {
sslContext =
new SSLContextBuilder().loadTrustMaterial(null, (x509Certificates, s) -> true).build();
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
LOG.error("Could not create ssl context", e);
}
builder.setSSLHostnameVerifier(new NoopHostnameVerifier()).setSSLContext(sslContext);
return builder.build();
}
可以参考以下文档,几乎包括了所有可能的配置:https://www.programcreek.com/java-api-examples/?api=org.apache.http.conn.ssl.NoopHostnameVerifier
三、feignclient
@Bean
public Client feignClient() {
SSLContext context = buildCertificateIgnoringSslContext();
Client trustSSLSockets = new Client.Default(context.getSocketFactory(), new NoopHostnameVerifier());
return trustSSLSockets;
}
public static SSLContext buildCertificateIgnoringSslContext() {
try {
return new SSLContextBuilder()
.loadTrustMaterial(null, (x509Certificates, s) -> true)
.build();
}
catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
throw new IllegalStateException("Unexpected exception while building the certificate-ignoring SSLContext.", e);
}
}