Avoid SSL in Apache HTTP client

Posted By: Matpal Media - 12:54 PM
Avoid SSL in Apache HTTP client. 

Sometimes,  you need to do REST call from Apache HTTP client where the REST endpoint has https. HTTPS may block your request since you are not a trusted party. To avoid such situation you can use following code ( This code should be only used in development and QA environment, not for production).


try
 {
    DefaultHttpClient client = new DefaultHttpClient();
    
    HostnameVerifier hostnameVerifier=
    org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    
    SchemeRegistry registry = new SchemeRegistry();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    registry.register(new Scheme("https", socketFactory, 443));
    
    SingleClientConnManager mgr = 
    new SingleClientConnManager(client.getParams(), registry);
    
    DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
    HttpGet requestAPI = new HttpGet(url);
    HttpResponse responseAPI = httpClient.execute(requestAPI);
    HttpEntity entity = responseAPI.getEntity();
    int responseCode = responseAPI.getStatusLine().getStatusCode();
 }
catch(Exception e) 
 {
 
 }

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.