How to access secure HTTPS webservice in Android

Posted By : Chandan Wadhwa | 25-Dec-2014

HTTPS webservice can be called after generating keystrore and storing in raw folder of android environment.

 

You will face error when accessing https service in android. The problem was “javax.net.ssl.SSLPeerUnverifiedException: No peer certificate” or “Handshake Exception” .

 

How to use the keystroke in your app for HTTP Response

 

 public class MySSLSocketFactory extends SSLSocketFactory {
	
	
	SSLContext sslContext = SSLContext.getInstance("SSLv3");
	
	public MySSLSocketFactory(KeyStore truststore)
			throws NoSuchAlgorithmException, KeyManagementException,
			KeyStoreException, UnrecoverableKeyException 
	{
		super(truststore);
		
	}
	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 {
		SSLSocket S = (SSLSocket) sslContext.getSocketFactory().createSocket(
				socket, host, port, autoClose);
		S.setEnabledProtocols(new String[] { "SSLv3" });
		return S;
	}

	@Override
	public Socket createSocket() throws IOException {
		SSLSocket S = (SSLSocket) sslContext.getSocketFactory().createSocket();
		S.setEnabledProtocols(new String[] { "SSLv3" });
		return S;
	}


	public static HttpClient getNewHttpClient() {
		try {
			InputStream in = context.getResources().openRawResource(R.raw.mykeystore);
				    
			KeyStore trustStore = KeyStore.getInstance(KeyStore
					.getDefaultType());
			trustStore.load(in,"sslcertificate".toCharArray());
			String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
			TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
			tmf.init(trustStore);
			// Create an SSLContext that uses our TrustManager
			SSLContext context = SSLContext.getInstance("TLS");
			context.init(null, tmf.getTrustManagers(), null);
			
			SSLSocketFactory sf = new SSLSocketFactory(trustStore);
		
            	SSLSocket s = (SSLSocket) sf.createSocket();
			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			s.startHandshake();
		
			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();
		}
	}
	
}

 

How to use the keystroke in your app for HTTP POST

 

override the getNewHttpCient() Method as below :

 

 public static HttpClient getNewHttpClient(HttpClient client) {
		try{
			   X509TrustManager x509TrustManager = new X509TrustManager() { 	           
					@Override
					public void checkClientTrusted(X509Certificate[] chain,
							String authType) throws CertificateException {
					}
	 
					@Override
					public void checkServerTrusted(X509Certificate[] chain,
							String authType) throws CertificateException {
					}
	 
					@Override
					public X509Certificate[] getAcceptedIssuers() {
						return null;
					}
		        };
		        
		        SSLContext sslContext = SSLContext.getInstance("TLS");
		        sslContext.init(null, new TrustManager[]{x509TrustManager}, null);
		        SSLSocketFactory sslSocketFactory = new MySSLSocketFactoryResponse(sslContext);
		        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		        ClientConnectionManager clientConnectionManager = client.getConnectionManager();
		        SchemeRegistry schemeRegistry = clientConnectionManager.getSchemeRegistry();
		        schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
		        return new DefaultHttpClient(clientConnectionManager, client.getParams());
		    } catch (Exception ex) {
		        return null;
		    }
			
	}

 

Thanks .

 

About Author

Author Image
Chandan Wadhwa

Chandan is an Android Apps developer with good experience in building native Android applications.

Request for Proposal

Name is required

Comment is required

Sending message..