Alin Huang Alin Huang - 7 days ago 5
Java Question

Any Apache HttpClient 4.4 Example for trust self signed certificates

I changed

HttpClient
version from old version to the new
4.4
.

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

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
        .custom()
        .setCookieSpec(CookieSpecs.DEFAULT)
        .setExpectContinueEnabled(true)
        .setTargetPreferredAuthSchemes(
                Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
        .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig)
        .setSocketTimeout(TIME_OUT).setConnectTimeout(TIME_OUT)
        .setConnectionRequestTimeout(TIME_OUT).build();
httpPost.setConfig(requestConfig);

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

response = httpclient.execute(httpPost);