1

I am trying to send a HTTP request to a server with a cookie attached to the httppost request as shown below:

public static void cookieRequest(String url, String cookie){


        try {


            CookieStore cookieStore = new BasicCookieStore();
            BasicClientCookie stdCookie = new BasicClientCookie("Cookie",cookie);
            cookieStore.addCookie(stdCookie);
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();

            localContext.setAttribute(ClientContext.COOKIE_STORE,
                    cookieStore);
            HttpPost httppost = new HttpPost(url);


            HttpResponse response = httpClient.execute(httppost, localContext);

            String result = EntityUtils.toString((HttpEntity) response);

            System.out.println("Cookie: "+ result);


        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

    }

But my log shows the following error:

    11-21 14:04:23.330: W/System.err(3552): java.lang.ClassCastException: org.apache.http.message.BasicHttpResponse cannot be cast to org.apache.http.HttpEntity
    11-21 14:04:23.335: W/System.err(3552):     at packageapp.util.Utils.cookieRequest(Utils.java:635)
    11-21 14:04:rop23.335: W/System.err(3552):  at package.app.packageMenu$loadingTask.doInBackground(packageMenu.java:482)
    11-21 14:04:23.340: W/System.err(3552):     at package.app.packageMenu$loadingTask.doInBackground(packageMenu.java:1)
    11-21 14:04:23.340: W/System.err(3552):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
    11-21 14:04:23.345: W/System.err(3552):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    11-21 14:04:23.345: W/System.err(3552):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    11-21 14:04:23.345: W/System.err(3552):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
    11-21 14:04:23.345: W/System.err(3552):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
    11-21 14:04:23.345: W/System.err(3552):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
    11-21 14:04:23.345: W/System.err(3552):     at java.lang.Thread.run(Thread.java:856)

Any idea?

update : this is my cookie:

[[version: 0][name: PHPSESSID][value: ec3e7cd62ae550880ecd25eb2b305d9e] 
[domain: rec.m.package.com][path: /][expiry: null], [version: 0][name: lang] 
[value: en][domain: .lpackagecom][path: /][expiry: Fri Nov 21 14:33:24 
UTC+04:00 2014], [version: 0][name: ci_session]
[value: v0z%2F8ANEAAOV8rbnyBRz%2FBIt2kMHAjNb3n7fTwyYwS4DDaI9DVmiiKAJBZpdCZHf6zopLjkpACAmQvKMj2NBhTIhK4Lss9fPgZ7UGyK3ONGXsK0eXdWECIgVFWB1TSRx0QQ3%2BBtDFLWJ1I7g26j8D603TjzSnMnfejlFZFWRFMm9xGX7fiC3qNuucFJyNTulyYzqQbH%2FCUZjRHSwT8MkplPLr7q6WhKmtsidXCFiYX3mPtJpMHyQL374c%2BWT0QOp14Au3NnjtrQyCx5v%2BpJXgboXTFMD7cqTrIpjHNZCLx4AVKa1IdbeTNvYgIXSYx8uo8pfKIZcvYSZbbRcvHP%2FAA%3D%3D]
[domain: .package.com][path: /][expiry: Sat Nov 23 14:33:24 UTC+04:00 2013]]

4 Answers 4

2

Try this way

EntityUtils.toString(response.getEntity())
Sign up to request clarification or add additional context in comments.

1 Comment

Maybe you should explain why this works and also where to integrate this into the given example.
0

Try Like this

String response = EntityUtils.toString(response.getEntity());
httpResponse.getEntity().consumeContent();
System.out.println("Cookie: "+ response);

3 Comments

is the way i set cookie ok ?
can you adapt it to my answer please the cookie is not working
0

Use this way:

            HttpEntity entity = response.getEntity();

            if (entity != null) {


                InputStream is = entity.getContent();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr, 1024 * 4);
                String line = null;
                while ( (line = br.readLine()) != null) {

                    buff.append(line).append("\n");

                }
                is.close();

But if you interesting to get Cookies from response, fetch them from httpclient:

mCookies = httpclient.getCookieStore().getCookies();

            if (mCookies.isEmpty()) {
                Log.d("test_runner", "Cookies: None");
            } else {
                for (int i = 0; i < mCookies.size(); i++) {

                    Log.d("test_runner", "Cookies: [" + i + "]" + mCookies.get(i).toString());
                }
            }

To store Cookies to next request use CookieStore:

     CookieStore cookieStore = new BasicCookieStore(); 

     for(Cookie cook : mCookies){
         cookieStore.addCookie(cook); 
     }

     httpclient = new DefaultHttpClient();
     httpclient.setCookieStore(cookieStore);

4 Comments

thanks i have already the cookie stored as a string. now i want to send the cookie with another http post request.
@Nikita see my edit I posted, To store Cookies to next request use ...
will the cookie be saved in the application ?
sure if you call HTTP request in the Service.
0
// try this
public  void cookieRequest(String url, String cookie){

        try {
            BasicClientCookie stdCookie = new BasicClientCookie("Cookie",cookie);
            LinkedList<Cookie> cookieList = new LinkedList<Cookie>();
            cookieList.add(stdCookie);
            HttpClient httpClient =getHttpclient(cookieList);
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpClient.execute(httppost);
            String result = getResponseBody(response.getEntity());
            System.out.println("Cookie: "+ result);


        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

}

public DefaultHttpClient getHttpclient(List<Cookie> cookies) {

        HttpParams httpParameters = new BasicHttpParams();
        DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);

        if (cookies != null) {
            int size = cookies.size();
            for (int i = 0; i < size; i++) {
                httpclient.getCookieStore().addCookie(cookies.get(i));
            }
        }
        return httpclient;
}

public String getResponseBody(final HttpEntity entity) throws IOException, ParseException {
        System.out.println("GEN START : " + Calendar.getInstance().getTimeInMillis());
        if (entity == null) {
            throw new IllegalArgumentException("HTTP entity may not be null");
        }

        InputStream instream = entity.getContent();

        if (instream == null) {
            return "";
        }

        if (entity.getContentLength() > Integer.MAX_VALUE) {
            throw new IllegalArgumentException(

                    "HTTP entity too large to be buffered in memory");
        }

        StringBuilder buffer = new StringBuilder();

        BufferedReader reader = new BufferedReader(new InputStreamReader(instream, HTTP.UTF_8));

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

        } finally {
            instream.close();
            reader.close();
        }
        System.out.println("GEN END : " + Calendar.getInstance().getTimeInMillis());
        return buffer.toString();

}

2 Comments

getting java.lang.ClassCastException: org.apache.http.message.BasicHttpResponse cannot be cast to org.apache.http.HttpEntity
thanks for your answer but when i post to server the session is expired. not getting right response there shoud be a problem with the cookie

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.