Sunday 27 October 2013

How to call HTTPS webservices in android




For Example :

==> First call following method.

public static void trustAllHosts() {

        X509TrustManager easyTrustManager = new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException {
                // Oh, I am easy!
            }

            public void checkServerTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException {
                // Oh, I am easy!
            }

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

        };

        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { easyTrustManager };

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");

            sc.init(null, trustAllCerts, new java.security.SecureRandom());

            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

====> After this


For calling HTTPS webservices you need to create Custom HttpClient instead of using DefaultHttpClient.


HttpClient _httpclient = Utils.getNewHttpClient();

Following is getNewHttpClient() method :



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

SSLSocketFactory sf = new MySSLSocketFactory(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();
}
}


Here we have use custom MySSLSocketFactory class, which is following.

Create new class MySSLSocketFactory.java copy following code and paste.







public class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");

public MySSLSocketFactory(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();
}
}

Now done :) You can parse your xml now. 



19 comments:

  1. Wonderful article, very useful and well explanation. Your post is extremely incredible. I will refer this to my candidates...
    SEO Training in Chennai

    ReplyDelete
  2. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    online Python training
    python training in chennai

    ReplyDelete
  3. This is a nice article here with some useful tips for those who are not used-to comment that frequently. Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.
    Data Science course in rajaji nagar
    Data Science with Python course in chenni
    Data Science course in electronic city
    Data Science course in USA
    Data science course in pune | Data Science Training institute in Pune

    ReplyDelete
  4. Really great post, Thank you for sharing This knowledge.Excellently written article, if only all bloggers offered the same level of content as you, the internet would be a much better place. Please keep it up!

    angularjs Training in btm

    angularjs Training in electronic-city

    angularjs online Training

    angularjs Training in marathahalli

    angularjs interview questions and answers

    angularjs Training in bangalore

    angularjs Training in bangalore

    ReplyDelete
  5. Thanks For sharing Your Information The Information shared Is Very Valuable Please Keep Updating Us Python Online Course Hadoop Online Course Data Science Online Course Aws Online Course

    ReplyDelete

  6. I enjoyed over read your blog post. Your blog have nice information, I got good ideas from this amazing blog. I am always searching like this type blog post. I hope I will see again.
    Still Hunting Method
    Hunting psych tips Survival Tips Travel Touring Tips

    ReplyDelete


  7. Thanks for sharing the information. It is very useful for my future. keep sharing travel trekking tips
    see the link Tent Camping 101 Exploring Smithriver

    ReplyDelete
  8. Bagian atas dalam permainan judi kartu oline ini memang memiliki nilai yang kecil jika dibandingkan dari susunan lainnya
    asikqq
    dewaqq
    sumoqq
    interqq
    pionpoker
    bandar ceme terpercaya
    hobiqq
    paito warna terlengkap
    bocoran sgp

    ReplyDelete
  9. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful .Manual Testing Training in Bangalore

    ReplyDelete
  10. I am happy for sharing on this blog its awesome blog I really impressed. thanks for sharing. Great efforts.

    Upgrade your career Learn Mulesoft Training in Bangalore from industry experts get Complete hands-on Training, Interview preparation, and Job Assistance at Softgen Infotech.

    ReplyDelete
  11. Excellant submit!!!.
    The strategy you've got published on this generation helped me to get into the subsequent stage and had lot of information in it..

    click here formore info.

    ReplyDelete
  12. I am obliged to you for sharing this piece of statistics
    here and updating us together with your inventive steerage.
    gomovies

    ReplyDelete
  13. thanks for sharing this good information

    BEST ANGULAR JS TRAINING IN CHENNAI WITH PLACEMENT

    https://www.acte.in/angular-js-training-in-chennai
    https://www.acte.in/angular-js-training-in-annanagar
    https://www.acte.in/angular-js-training-in-omr
    https://www.acte.in/angular-js-training-in-porur
    https://www.acte.in/angular-js-training-in-tambaram
    https://www.acte.in/angular-js-training-in-velachery

    ReplyDelete
  14. Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!
    Angular js Training in Chennai

    Angular js Training in Velachery

    Angular js Training in Tambaram

    Angular js Training in Porur

    Angular js Training in Omr

    Angular js Training in Annanagar

    ReplyDelete