Monday, December 9, 2013

How To call HTTPS web services in android.

1.First You have to create a custom httpclient  in a class like:-

import java.security.KeyStore;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;



public class HttpsClient {
public static HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
trustStore.load(null, null);

SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

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();
}
}

}


2.Then creare a ssl factory class like:-

import java.io.IOException; 
import java.net.Socket; 
import java.net.UnknownHostException; 
import java.security.KeyManagementException; 
import java.security.KeyStore; 
import java.security.KeyStoreException; 
import java.security.NoSuchAlgorithmException; 
import java.security.UnrecoverableKeyException; 
import java.security.cert.CertificateException; 
import java.security.cert.X509Certificate; 

import javax.net.ssl.SSLContext; 
import javax.net.ssl.TrustManager; 
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.ssl.SSLSocketFactory;

public class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
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 {
return sslContext.getSocketFactory().createSocket(socket, host, port,
autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}

3. create a method ( trustAllHosts() )to valide your certificates like:-

public static void trustAllHosts() {
X509TrustManager easyTrustManager = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException {
                // Oh, I am easy!
            }

            public void checkServerTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException {
                // Oh, I am easy!
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

};
  // Create a trust manager that does not validate certificate chains
           TrustManager[] trustAllCerts = new TrustManager[] { easyTrustManager };
           // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }

}


4.in your activity ,send data to server using post request like:-

BasicNameValuePair _emailpair = new BasicNameValuePair("email", email);
            BasicNameValuePair _passwordpair = new BasicNameValuePair("password",password);
            List<NameValuePair> _namevalueList = new ArrayList<NameValuePair>();
            _namevalueList.add(_emailpair);
            _namevalueList.add(_passwordpair);
            String response=SendData(url_login,_namevalueList);
            Log.e("===RESPONSE====>","===RESPONSE====>"+response);

//here is the SendData MEthod
//everytime when you hit any request either it is get or post,you have to call trustAllHosts() method;

public String SendData(String url, List<NameValuePair> _namevalueList) {
String _Response = null;
trustAllHosts() ;
HttpClient _httpclient = HttpsClient.getNewHttpClient();
HttpPost _httppost = new HttpPost(url);
        try {
        _httppost.setEntity(new UrlEncodedFormEntity(_namevalueList, HTTP.UTF_8));
    HttpResponse _httpresponse = _httpclient.execute(_httppost);
    int _responsecode = _httpresponse.getStatusLine().getStatusCode();
    Log.i("--------------Responsecode----------", "." + _responsecode);
    if (_responsecode == 200) {
                    InputStream _inputstream = _httpresponse.getEntity().getContent();
                    BufferedReader r = new BufferedReader(new InputStreamReader(_inputstream));
                    StringBuilder total = new StringBuilder();
                    String line;
                    while ((line = r.readLine()) != null) {
                            total.append(line);
                    }
                    _Response = total.toString();
                    } else {
                    _Response = "Error";
                    }
        } catch (Exception e) {
        e.printStackTrace();
        }
    return _Response;
}

///// get request syntax is:-

public void GetAll_Products_List(String url_get_all_products_list) {
trustAllHosts() ;
HttpClient _httpclient = HttpsClient.getNewHttpClient();
HttpGet _httpget = new HttpGet(url_get_all_products_list);
try {
HttpResponse _httpresponse = _httpclient.execute(_httpget);
int _responsecode = _httpresponse.getStatusLine().getStatusCode();
Log.i("--------------Responsecode----------", "." + _responsecode);
if (_responsecode == 200) {
InputStream _inputstream = _httpresponse.getEntity().getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(_inputstream));
StringBuilder total = new StringBuilder();
                 String line;
                 while ((line = r.readLine()) != null) {
                         total.append(line);
                 }
                 String G_P_L = total.toString();
                 System.out.println(G_P_L);
}
} catch (Exception e) {
e.printStackTrace();
}
}else{
System.out.println("error");
}
} catch (Exception e) {
e.printStackTrace();
}
}

f

No comments:

Post a Comment