Android HttpClient self-certificate

Android HttpClient

Above Android 5, HttpURLConnection(java.net.HttpURLConnection) seems to be main HttpClient for Android.
(Apache HttpClient is deprecated)

These days, mobile application access server and
We provide service both web and mobile, or save and keep data in server.
We need to prepare server to communicate with mobile. This is not only Production but also Test.
In production, we need to prepare SSL for security, but for test, what do you think?

SSL is not cheap, so some times we don’t prepare and use self-certificate

In WebView, it is different. I will explain it in other entry.

HttpsURLConnection and ignore certificate errors

For https connection, we need to use HttpsURLConnection

public static HttpURLConnection getHttpsConnection(URL url) throws IOException {
     HttpURLConnection conn = null;
     if (url == null) return conn;
     
     conn = (HttpsURLConnection)url.openConnection();
     // Ignore
     ((HttpsURLConnection)conn).setHostnameVerifier(new HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession sslSession) {
                        return true;
                    }
                });
     KeyManager[] keyManagers = null;
     TrustManager[] transManagers = { 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;
                    }
     } };
     try {
                    SSLContext sslcontext = SSLContext.getInstance("SSL");
                    sslcontext.init(keyManagers, transManagers, new SecureRandom());
                    ((HttpsURLConnection)conn).setSSLSocketFactory(sslcontext.getSocketFactory());
     }
     catch (NoSuchAlgorithmException e) {
                    Log.w("TAG", "Failed to create SSL Context");
     }
     catch (KeyManagementException e) {
                    Log.w("TAG", "Failed to create SSL Context");
     }
}