11

When I want to open an HTTPS connection I get SSL Exception. How to set HttpURLConnection in a way to doesn't be sensitive to this exception?

My code is:

private String getData() {
    String response = null;
    String connection = "https://www.kamalan.com/";

    try {
        URL url = new URL(connection);
        Log.i(TAG, "Try to open: " + connection);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        int responseCode = conn.getResponseCode();
        Log.i(TAG, "Response code is: " + responseCode);
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            if (in != null) {
                StringBuilder strBuilder = new StringBuilder();             
                int ch = 0;
                while ((ch = in.read()) != -1)
                    strBuilder.append((char) ch);

                // get returned message and show it
                response = strBuilder.toString();
                Log.i("JSON returned by server:", response);
            }

            in.close();

        } else {
            Log.e(TAG, "Couldn't open connection in getResepiItems()");
        }
    } catch (SSLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;
}
user207421
  • 305,947
  • 44
  • 307
  • 483
Hesam
  • 52,260
  • 74
  • 224
  • 365
  • @Morrison Chang This is the error in log cat `Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.` – RajaReddy PolamReddy Aug 29 '12 at 04:10
  • 1
    Have you see this SO post:http://stackoverflow.com/questions/6825226/trust-anchor-not-found-for-android-ssl-connection ? – Morrison Chang Aug 29 '12 at 04:32
  • thanks Morrison and Raja, I changed my method from opening connection to loading into webView and getting data over there. However thanks for your suggestion. If I back to above method then I'll test it. – Hesam Aug 29 '12 at 05:01
  • 4
    @Hesam Don't. It is insecure. Solve the certificate deployment problem, don't just wire a bypass around it. Certificate checking is a critical part of SSL security. – user207421 Aug 29 '12 at 05:10
  • @EJP can you look at this Question http://stackoverflow.com/questions/12136907/how-to-create-an-https-connection i am also looking for solution for Https.. – RajaReddy PolamReddy Aug 29 '12 at 05:29
  • based on my research some people solved their similar problem with using System.setProperty("http.keepAlive", "false"); before HttpurlConnection definition. However, It wasn't work for me. http://stackoverflow.com/questions/5491216/android-ssl-error-certificate-not-trusted-sometimes – Hesam Aug 29 '12 at 06:01
  • System.setProperty("https.keepAlive", "false"); didn't work for me as well. – Hesam Aug 29 '12 at 06:01
  • I got solution for this can you look at this once [How to create an https Connection?][1] [1]: http://stackoverflow.com/questions/12136907/how-to-create-an-https-connection – RajaReddy PolamReddy Aug 29 '12 at 09:01
  • @RajaReddyPolamReddy Look, at it why? – user207421 May 05 '16 at 10:04
  • 2
    @Hesam You are mistaken. You cannot solve a certificate problem with HTTP keep-alive. – user207421 Jun 05 '16 at 09:48

1 Answers1

3

Follow the below method, it works for me.

        URL url = new URL("Your URL");
        HttpsURLConnection urlConnection =(HttpsURLConnection) url.openConnection();    urlConnection.setSSLSocketFactory(SSLCertificateSocketFactory.getInsecure(0, null));
        urlConnection.setHostnameVerifier(getHostnameVerifier());
        InputStream is = urlConnection.getInputStream();
        OutputStream os = new FileOutputStream(downloadedFile);
        byte[] data = new byte[1024];
        int count;
        while ((count = is.read(data)) != -1) {
            os.write(data, 0, count);
        }
        os.flush();
        os.close();
        is.close();

The below method for set the Hostname

private HostnameVerifier getHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                HostnameVerifier hv =
                        HttpsURLConnection.getDefaultHostnameVerifier();
                return hv.verify("com.example.com", session);
            }
        };
        return hostnameVerifier;
    }
user207421
  • 305,947
  • 44
  • 307
  • 483
Raja Jawahar
  • 6,742
  • 9
  • 45
  • 56
  • 4
    It works how? And why? All this nonsense amounts to nothing more than verifying the session against a fixed hostname. The point, if there is one, is not stated. Don't use quote formatting for text that isn't quoted, – user207421 May 05 '16 at 10:03