Alin Huang Alin Huang - 1 year ago 87
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.

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download