Alin Huang Alin Huang - 3 months ago 24
Java Question

Any Apache HttpClient 4.4 Example for trust self signed certificates

I changed

version from old version to the new

And got many deprecated method and Class. The original codes can trust self signed certificates and I want to replace to new method and Class.

Could any one give me a guide line how to replace or any example code?

Thank you.


Thanks for reply, I found a sample code as below

SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null,
        new TrustSelfSignedStrategy()).build();

// Allow TLSv1 protocol only, use NoopHostnameVerifier to trust self-singed cert
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
        new String[] { "TLSv1" }, null, new NoopHostnameVerifier());

//do not set connection manager
httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

HttpPost httpPost = new HttpPost(url);

RequestConfig defaultRequestConfig = RequestConfig
                Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig)

httpPost.setHeader("Content-type", "application/json");
StringEntity mEntity = new StringEntity(arg, "UTF-8");
mEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,

response = httpclient.execute(httpPost);