Sunday 22 July 2012

Working with HttpsUrlConnection


Refer this doc over HttpsUrlConnection.
To create key and import certificate use Portecle tool.
To create key using Keytool, follow the doc.


String query = "emailId=" + URLEncoder.encode("xxx@gmail.com", HTTP.UTF_8) + "&pwd=" + URLEncoder.encode("password", HTTP.UTF_8);


HttpsURLConnection urlConnection = null;
try{
    KeyStore keyStore = KeyStore.getInstance("BKS");
    InputStream in =  
    getResources().openRawResource(R.raw.keystore);
    keyStore.load(in, "password".toCharArray());
    TrustManagerFactory tmf = 
    TrustManagerFactory.getInstance("X509");
    tmf.init(keyStore);


    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);
    System.setProperty("http.keepAlive", "false");
    URL url = new URL("https://www.google.co.in/");
    urlConnection = (HttpsURLConnection) url.openConnection();
     
urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("content-type",
    "application/x-www-form-urlencoded");
    urlConnection.setRequestProperty("Content-length", "" +  query.getBytes().length);

     //To post data...
     DataOutputStream output = new DataOutputStream( urlConnection.getOutputStream() );
     output.writeBytes( query );
     output.flush();
     output.close();

     InputStream stream = null;


     if ( urlConnection.getResponseCode() == 201 )
stream = urlConnection.getInputStream();
     else
       //Report error...

     urlConnection.disconnect();


}catch(Exception e){
     urlConnection.disconnect();
}



profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

No comments:

Post a Comment