Search code examples
androidgettext

httpget not working due to "not trusted server certificate" but it works with httpost


I have a code that needs to go to the website below and extract the text. In another part of the project I use the httpost method and it gives me a response based on what I've sent. However for the httpget function suddenly it gives me an exception saying javax.net.ssl.SSLEXCEPTION:Not trusted server certificate.

Is there a way to fix this? I don't understand why one method works while the other doesn't. Thanks

     //some code
    getText("https://iphone-radar.com/accounts/4e3f2c6659f25a0f8400000b");

}
    public static void getText(String uri) {

        HttpClient httpclient = new DefaultHttpClient();

        // Prepare a request object
        HttpGet httpget = new HttpGet(uri); 

        // Execute the request
        HttpResponse response;
        try {
            response = httpclient.execute(httpget);
            // Examine the response status


            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            android.util.Log.v("EXCEPTION","["+e.getMessage()+"]", e);



        }
    }

Solution

  • I had a similar problem while developing an app for my school. The trick is to create two classes that override certificate verification. One extends HostnameVerifier and returns true every time verify() is called, like this. The other class extends X509TrustManager and overrides getAcceptedIssuers() like this.

    Then you can set the HttpsURLConnection to accept all certificates using this code:

    HttpsURLConnection.setDefaultHostnameVerifier(new AllVerifier());
    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { new AllTrustManager() }, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    

    That should do the trick. You can see how I used this code here, in the run() method.