Skip to content

Commit b2f8ee1

Browse files
committed
#248 httpclient请求时忽略掉对服务器端证书的校验,以避免某些情况下微信请求会出现40029或443 failed to respond的问题
1 parent 007e736 commit b2f8ee1

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/DefaultApacheHttpClientBuilder.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,24 @@
1414
import org.apache.http.conn.socket.ConnectionSocketFactory;
1515
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
1616
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
17+
import org.apache.http.conn.ssl.TrustStrategy;
1718
import org.apache.http.impl.client.BasicCredentialsProvider;
1819
import org.apache.http.impl.client.CloseableHttpClient;
1920
import org.apache.http.impl.client.HttpClientBuilder;
2021
import org.apache.http.impl.client.HttpClients;
2122
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
2223
import org.apache.http.protocol.HttpContext;
24+
import org.apache.http.ssl.SSLContexts;
2325
import org.slf4j.Logger;
2426
import org.slf4j.LoggerFactory;
2527

28+
import javax.net.ssl.SSLContext;
2629
import java.io.IOException;
30+
import java.security.KeyManagementException;
31+
import java.security.KeyStoreException;
32+
import java.security.NoSuchAlgorithmException;
33+
import java.security.cert.CertificateException;
34+
import java.security.cert.X509Certificate;
2735
import java.util.concurrent.TimeUnit;
2836
import java.util.concurrent.atomic.AtomicBoolean;
2937

@@ -214,6 +222,7 @@ private synchronized void prepare() {
214222
this.httpClientBuilder = HttpClients.custom()
215223
.setConnectionManager(connectionManager)
216224
.setConnectionManagerShared(true)
225+
.setSSLSocketFactory(this.buildSSLConnectionSocketFactory())
217226
.setDefaultRequestConfig(
218227
RequestConfig.custom()
219228
.setSocketTimeout(this.soTimeout)
@@ -240,6 +249,29 @@ private synchronized void prepare() {
240249
prepared.set(true);
241250
}
242251

252+
private SSLConnectionSocketFactory buildSSLConnectionSocketFactory() {
253+
try {
254+
SSLContext sslcontext = SSLContexts.custom()
255+
//忽略掉对服务器端证书的校验
256+
.loadTrustMaterial(new TrustStrategy() {
257+
@Override
258+
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
259+
return true;
260+
}
261+
}).build();
262+
263+
return new SSLConnectionSocketFactory(
264+
sslcontext,
265+
new String[]{"TLSv1"},
266+
null,
267+
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
268+
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
269+
this.log.error(e.getMessage(), e);
270+
}
271+
272+
return null;
273+
}
274+
243275
@Override
244276
public CloseableHttpClient build() {
245277
if (!prepared.get()) {

0 commit comments

Comments
 (0)