Wednesday, January 18, 2012

How to store cookie in Android execute post and attach with url

following methods make global application context for http Reques & Response


 /** Single instance of our HttpClient */
    private static HttpClient mHttpClient;
    private static HttpContext mHttpContext;
    private static Bitmap bitmap;

    public static Cookie mSessionCookie;

    static String TAG="CustomHttpClient";

    /**
     * Get our single instance of our HttpClient object.
     *
     * @return an HttpClient object with connection parameters set
     */
    public static HttpClient getHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
           
            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }
        return mHttpClient;
    }
private static HttpContext getHttpContext(){
    if(mHttpContext==null){
        mHttpContext=new BasicHttpContext();
    }
    return mHttpContext;
}




storing cookie in execute post method.



public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            // Create a local instance of cookie store
            CookieStore cookieStore = new BasicCookieStore();
            // Create local HTTP context
            HttpContext localContext=getHttpContext();
            // Bind custom cookie store to the local context
            localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
           
            HttpPost request = new HttpPost(url);
         
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            Log.e( "postParameters",""+ postParameters);
            Log.e("formEntity",""+formEntity);

            /*    MultipartEntity entity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.JPEG, 100, bos);
            byte[] data = bos.toByteArray();
            entity.addPart("returnformat", new StringBody("json"));
            entity.addPart("uploaded", new ByteArrayBody(data,
                    "myImage.jpg"));*/
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request,localContext);
            //HttpResponse response = client.execute(request);
            Log.e("headers",""+response.headerIterator());
           //String mSessionId=null;
          //  Log.e("mSessionId",""+mSessionId);
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator());
            while (it.hasNext()) {
                HeaderElement elem = it.nextElement();
                System.out.println(elem.getName() + " = " + elem.getValue());
                if(elem.getName().equals("JSESSIONID")){
                    NetworkManager.mSessionId=elem.getValue();
                }
                NameValuePair[] params = elem.getParameters();
                for (int i = 0; i < params.length; i++) {
                    System.out.println(" " + params[i]);
                }
            }

           
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            List<Cookie> cookies = cookieStore.getCookies();
            Log.e("CustomHttpClient","Cookies size= " + cookies.size());
            for (int i = 0; i < cookies.size(); i++) {
                Cookie cookie = cookies.get(i);
                Log.e("CustomHttpClient","Local cookie: " + cookie);
                mSessionCookie = cookie;
                Log.e("CustomHttpClient",""+cookie.getValue());
            }
           
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


follwing class where we using stored cookie to attach with url to launch url in webview .store that cookiew in Application class in android and retrive where ever you are using.

WebClinetforPaypa.java


package com.inception.smui;

import org.apache.http.cookie.Cookie;


import com.ServiceMessenger.R;
import com.inception.dataparser.Configure;
import com.inception.dataparser.JSONSMParser;
import com.inception.network.CustomHttpClient;
import com.inception.sm.MyAppContext;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;

import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

public class WebClinetforPaypal extends Activity{
    WebView mWebview;
    MyAppContext mAppctx;
    String url_paypal;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);
        mAppctx = (MyAppContext)getApplicationContext();       
        Intent i=getIntent();
        url_paypal=(String) i.getCharSequenceExtra("url");

        mWebview = (WebView) findViewById(R.id.web_engine);

        new WebViewTask().execute();


    }
    private class WebViewTask extends AsyncTask<Void, Void, Boolean> { 
        Cookie sessionCookie; 
        CookieManager cookieManager; 

        @Override 
        protected void onPreExecute() { 
            CookieSyncManager.createInstance(WebClinetforPaypal.this); 
            cookieManager = CookieManager.getInstance(); 

            sessionCookie = mAppctx.getMySessionCookie(); 
            Log.i("sessionCookie",""+sessionCookie);
            if (sessionCookie != null) { 
                // delete old cookies 
                cookieManager.setAcceptCookie(true);
                cookieManager.removeSessionCookie(); 
            } 
            super.onPreExecute(); 
        } 
        protected Boolean doInBackground(Void... param) { 
            // this is very important - THIS IS THE HACK 
            SystemClock.sleep(1000); 
            return false; 
        } 
        @Override 
        protected void onPostExecute(Boolean result) { 
            if (sessionCookie != null) { 
                //cookieManager.setCookie("http://50.28.26.182/SMS_rajesh", sessionCookie.getName() +"="+sessionCookie.getValue()+"; domain="+sessionCookie.getDomain());
                cookieManager.setCookie(Configure.SM_SERVER_DOMAIN_NAME+"/"+
                        Configure.SM_SERVER_WAR_FILE_NAME, sessionCookie.getName() +
                        "="+sessionCookie.getValue()+"; domain="+
                                sessionCookie.getDomain()); 
                CookieSyncManager.getInstance().sync(); 
            } 
            mWebview.getSettings().setJavaScriptEnabled(true);
            mWebview.setWebViewClient(new WebViewClient() { 
                @Override 
                public boolean shouldOverrideUrlLoading(WebView view, String url) { 
                    return super.shouldOverrideUrlLoading(view, url); 
                } 

            });

           
            /* mWebview.setWebViewClient(new WebViewClient() {
                    @Override
                    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
                    {
                        // Handle the error
                    }

                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String url)
                    {
                        view.loadUrl(url);
                        return true;
                    }
                    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                        if (url.contains(".json")) {
                            return getCssWebResourceResponseFromAsset();
                        } else {
                            return super.shouldInterceptRequest(view, url);
                        }

                        }

                });*/
            mWebview.loadUrl(url_paypal);
           
            /*try {
                    String getPaypalResponse=CustomHttpClient.executeHttpGet(url_paypal);
                    String status=JSONSMParser.parseStatus(getPaypalResponse);
                    Log.d("payResponse",getPaypalResponse);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }*/
        } 
    }
}

following methods which execute other http get & post methods.

 http get.

/**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpGet(String url) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpGet request = new HttpGet();
            HttpContext localContext=getHttpContext();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request,localContext);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            Log.e("headers",""+response.headerIterator());
            //String mSessionId=null;
           //  Log.e("mSessionId",""+mSessionId);
             HeaderElementIterator it = new BasicHeaderElementIterator(
                     response.headerIterator());
             while (it.hasNext()) {
                 HeaderElement elem = it.nextElement();
                 System.out.println(elem.getName() + " = " + elem.getValue());
                 if(elem.getName().equals("JSESSIONID")){
                     NetworkManager.mSessionId=elem.getValue();
                 }
                 NameValuePair[] params = elem.getParameters();
                 for (int i = 0; i < params.length; i++) {
                     System.out.println(" " + params[i]);
                 }
             }

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}




following code to send multipart request 


 public static String executeHttpPost1(String url,ArrayList<NameValuePair> postParameters ) throws Exception {
        HttpPost post = new HttpPost(url);
      
        Bitmap bitmap; 
           String Result_STR=null;
            HttpClient client = getHttpClient();
            HttpContext localContext=getHttpContext();
           HttpEntity resmarkMessagesReadFrom =null;
           MultipartEntity reqmarkMessagesReadFrom = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
           try {
               Log.e(TAG+"postParameters.size()",""+postParameters.size());
               for(int i=0;i<postParameters.size();i++){
                   Log.e(TAG+"parameters",""+postParameters.get(i).getName()+""+postParameters.get(i).getValue());
                  
                   if(postParameters.get(i).getName().equals("spProfilePic")){
                       bitmap = BitmapFactory.decodeFile(postParameters.get(i).getValue()); 

                       // you can change the format of you image compressed for what do you want; 
                       //now it is set up to 640 x 480; 

                       Bitmap bmpCompressed = Bitmap.createScaledBitmap(bitmap, 640, 480, true); 
                       ByteArrayOutputStream bos = new ByteArrayOutputStream(); 

                       // CompressFormat set up to JPG, you can change to PNG or whatever you want; 

                       bmpCompressed.compress(CompressFormat.JPEG, 100, bos); 
                       byte[] data = bos.toByteArray();
                       Log.e(TAG,"data"+data);     
                       reqmarkMessagesReadFrom.addPart(postParameters.get(i).getName(), new ByteArrayBody(data, "temp.jpg")); 
                       Log.e(TAG,"bitmap"+bitmap);     

                   }
                   else
                       reqmarkMessagesReadFrom.addPart(postParameters.get(i).getName(), new StringBody(postParameters.get(i).getValue()));
              

               }
               post.setEntity(reqmarkMessagesReadFrom);
               Log.e(TAG,"after for loop"+post.getEntity());
                HttpResponse response = client.execute(post,localContext);
                Log.e("headers",""+response.getAllHeaders());
                 resmarkMessagesReadFrom = response.getEntity();
               if (resmarkMessagesReadFrom != null) {
                   Result_STR=EntityUtils.toString(resmarkMessagesReadFrom);
                  // mMSGBox.setText(Result_STR);
               }
           }
           catch(Exception e){
               Log.e(TAG,e.toString());
           }
           finally {
              
               }
          
   return Result_STR;
    }



/**
     * This method connects to server through HTTP request .(simple http request).
     */
    private static String connect(String url){

        // Create the httpclient
        //HttpClient httpclient = new DefaultHttpClient();
        DefaultHttpClient httpclient = new DefaultHttpClient();

        // Prepare a request object
        HttpGet httpget = new HttpGet(url);
       
        //Header h="JSESSIONID";
        //HttpRequest req=null;
        //req.addHeader("JSESSIONID",mSessionId);
   
       
        httpget.getAllHeaders();
         HeaderElementIterator it1 = new BasicHeaderElementIterator(
                 httpget.headerIterator());
         System.out.println(httpget.getURI());

         while (it1.hasNext()) {
             HeaderElement elem = it1.nextElement();
           
             NameValuePair[] params = elem.getParameters();
             for (int i = 0; i < params.length; i++) {
                 System.out.println(" " + params[i]);
             }
         }
        // Execute the request
        HttpResponse response;

        // return string
        String returnString = null;

        try {

            // Open the webpage.
            response = httpclient.execute(httpget);

            //        if(response.getStatusLine().getStatusCode() == 200){
            if(true) {
                // Connection was established. Get the content.

                HttpEntity entity = response.getEntity();
                //SetCookie c=new Cookie();
                //SetCookie.setValue(mSessionId);
                response.getAllHeaders();
                Log.e(TAG,"headers"+response.getAllHeaders());
                 HeaderElementIterator it = new BasicHeaderElementIterator(
                            response.headerIterator());
                    while (it.hasNext()) {
                        HeaderElement elem = it.nextElement();
                        System.out.println(elem.getName() + " = " + elem.getValue());
                        NameValuePair[] params = elem.getParameters();
                        for (int i = 0; i < params.length; i++) {
                            System.out.println(" " + params[i]);
                        }
                    }
                // If the response does not enclose an entity, there is no need
                // to worry about connection release

                if (entity != null) {
                    // A Simple JSON Response Read
                    InputStream instream = entity.getContent();

                    // Load the requested page converted to a string into a JSONObject.
                    //    JSONObject myAwway = new JSONObject(convertStreamToString(instream));
                    returnString = convertStreamToString(instream);
                    //    Log.e(TAG,"instream  : "+convertStreamToString(instream));
                    //        Log.e(TAG,"myawway  : "+ myAwway);

                    // Get the query value'
                    //String query = myAwway.getString("query");
                    //    JSONObject menuObject =myAwway.getJSONObject("photos");
                    // Make array of the suggestions
                    //        JSONArray suggestions =menuObject.getJSONArray("photo");

                    // Build the return string.
                    //                    returnString = "Found: " + suggestions.length() ;
                    //                for (int i = 0; i < suggestions.length(); i++) {
                    //                    returnString += "\n\t" +(suggestions.getJSONObject(i).getString("id").toString());
                    //                }
                    //    returnString = "Found";
                    // Cose the stream.
                    instream.close();

                }
            }
            else {
                // code here for a response othet than 200.  A response 200 means the webpage was ok
                // Other codes include 404 - not found, 301 - redirect etc...
                // Display the response line.
                returnString = "Unable to load page - " + response.getStatusLine();
            }
            return returnString ; 
        }
        catch (IOException  ex) {
            // thrown by line 80 - getContent();
            // Connection was not established
            returnString = "Connection failed; " + ex.getMessage();
        }
        //        catch (JSONException ex){
        // JSON errors
        //            returnString = "JSON failed; " + ex.getMessage();
        //        }
        return returnString;
    }

1 comment:

  1. nice post....will u please clear a doubt ? Whats the class MyAppContext? n how are u retrieving session cookie thru its object?

    ReplyDelete