Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make Unirest(java) ignore certificate error

I am using Unirest (java version) to make GET and POST request.But I encounter a problem when accessing SSL encrypted site , since my program is behind a corporate network and the network admin setup a firewall mapping for me. For example foobar.com is mapped to 56.1.89.12:4444. But when I make request to the address, I will received the following ssl certificate error:

com.mashape.unirest.http.exceptions.UnirestException: javax.net.ssl.SSLException: hostname in certificate didn't match: <56.1.89.12> != <www.foobar.com>
    at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:131)
    at com.mashape.unirest.request.BaseRequest.asString(BaseRequest.java:52)

I see Unirest has advance configuration to use custom httpclient.So I use

Unirest.setHttpClient(MyHttpClient.makeClient());
HttpResponse<String> res = null;
try {
    res = Unirest.get(urlstr).asString();
} catch (UnirestException e) {
    e.printStackTrace();
}
String jsonstr = res.getBody();

the makeClient method of MyHttpClient is:

public static HttpClient makeClient(){
 SSLContextBuilder builder = new SSLContextBuilder();
 CloseableHttpClient httpclient = null;
    try {
        // builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        builder.loadTrustMaterial(null, new TrustStrategy(){
            public boolean isTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
                return true;
            }
        });
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                builder.build());
        httpclient = HttpClients.custom().setSSLSocketFactory(
                sslsf).build();
        System.out.println("custom httpclient called");
        System.out.println(httpclient);

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

return httpclient;
}

the main idea is taken from Ignoring SSL certificate in Apache HttpClient 4.3

But still this didn't work.Any suggestions?

like image 766
Allan Ruin Avatar asked Apr 23 '14 10:04

Allan Ruin


1 Answers

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

    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom()
            .setSSLSocketFactory(sslsf)
            .build();
    Unirest.setHttpClient(httpclient);

this worked for me

like image 121
Maciej Mioduszewski Avatar answered Sep 19 '22 21:09

Maciej Mioduszewski