Tuesday, 28 July 2015

Android Trusting all certificates using HttpClient over HTTPS| Access all secure and in-secure https connection in Android and Java

Hello Friends,
          Today, I am going to share a blog post on "HTTPS". Using this blog we can easily access all
secure and non secure "HTTPS" connection in java as well as android too.


1. Add "InSecureSSLSocketFactory.java" class

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.ssl.SSLSocketFactory;
public class InSecureSSLSocketFactory extends SSLSocketFactory {
    SSLContext sslContext = SSLContext.getInstance("TLS");

    public InSecureSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
        super(truststore);

        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sslContext.init(null, new TrustManager[] { tm }, null);
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
        return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }
} 


2. Create a new HTTP client using the above InSecureSSLSocketFactory class, for making
     connection.

public HttpClient getNewHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        InSecureSSLSocketFactory sf = new InSecureSSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}
3. Finally hitting the service url(https://) using getNewHttpClient() , which helps to feth data
    from server.

public static String networkHitForGetJsonData(String url)
{
 String websiteData = null;
 try {
  HttpParams httpParameters = new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
  HttpClient client = getNewHttpClient();
  URI uri = new URI(url);
  HttpGet method = new HttpGet(uri);
  method.addHeader("Content-Type", "text/html");
  HttpResponse res = client.execute(method);
  InputStream data = res.getEntity().getContent();
  websiteData = generateString(data);
  Log.e("response","response---> "+websiteData);
 } catch (ClientProtocolException e) {
  e.printStackTrace();
  websiteData = null;
 } catch (IOException e)
 {
  e.printStackTrace();
  websiteData = null;
 } catch (URISyntaxException e)
 {
  e.printStackTrace();
  websiteData = null;
 }
 return websiteData;
}  



Hope, this will helps some one.
Enjoy coding....... :)

Mukesh Yadav

Hi Guys I am from Delhi working as Web/Mobile Application Developer(Android Developer), also have knowledge of Roboelctric and Mockito ,android test driven development... Blogging has been my passion and I think blogging is one of the powerful medium to share knowledge and ideas....

0 comments:

Post a Comment

 

Copyright @ 2013 Android Developer Blog.

Blog Widget by LinkWithin