Trusting all certificates using HttpClient over HTTPS

后端 未结 21 3074
北恋
北恋 2020-11-21 04:50

Recently posted a question regarding the HttpClient over Https (found here). I\'ve made some headway, but I\'ve run into new issues. As with my last problem, I

21条回答
  •  天命终不由人
    2020-11-21 05:32

    I'm adding a response for those that use the httpclient-4.5, and probably works for 4.4 as well.

    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.HttpResponseException;
    import org.apache.http.client.fluent.ContentResponseHandler;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.conn.ssl.NoopHostnameVerifier;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.conn.ssl.TrustStrategy;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.ssl.SSLContextBuilder;
    
    
    
    public class HttpClientUtils{
    
    public static HttpClient getHttpClientWithoutSslValidation_UsingHttpClient_4_5_2() {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            });
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), new NoopHostnameVerifier());
            CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); 
            return httpclient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    }
    

提交回复
热议问题