不過在測試階段時,有時會因為證書是用自我驗證來產生的,導致程式碼無法正常運作
HttpClient 有設定方法可以忽略這些認證資訊~
不過在 HttpClient 4.3 版以後,陸續有些類別和方法都被廢棄了
以下是在 HttpClient 4.5 版的設定方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
CloseableHttpClient HTTP_CLIENT = null ; try { // TODO Ignore the SSL certificate and host name verifier which should not be ignored in production. SSLContextBuilder sslBuilder = new SSLContextBuilder(); sslBuilder.loadTrustMaterial( null , new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslBuilder.build(), new TrustAllHostNameVerifier()); HTTP_CLIENT = HttpClients.custom().setSSLSocketFactory(sslsf).build(); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { e.printStackTrace(); } |
1 2 3 4 5 |
private static class TrustAllHostNameVerifier implements HostnameVerifier { public boolean verify(String hostname, SSLSession session) { return true ; } } |
參考資料:
沒有留言:
張貼留言