Android examples for Network:HTTPS SSL
get Http/Https URL Connection
//package com.java2s; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; public class Main { private static SSLContext sslcontext; private static HostnameVerifier hostnameVerifier; private static HttpURLConnection getHttpURLConnection(URL url) throws IOException { HttpURLConnection conn;//w ww . j a v a 2s . co m if (url.toString().startsWith("https")) { HttpsURLConnection connection = (HttpsURLConnection) url .openConnection(); connection.setSSLSocketFactory(getSslcontext() .getSocketFactory()); connection.setHostnameVerifier(getHostnameVerifier()); conn = connection; } else { conn = (HttpURLConnection) url.openConnection(); } return conn; } private static SSLContext getSslcontext() { if (sslcontext == null) { TrustManager trustManager = new X509TrustManager() { @Override public void checkClientTrusted( X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted( X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; try { sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[] { trustManager }, new java.security.SecureRandom()); } catch (NoSuchAlgorithmException | KeyManagementException e) { e.printStackTrace(); } } return sslcontext; } private static HostnameVerifier getHostnameVerifier() { if (hostnameVerifier == null) { hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }; } return hostnameVerifier; } }