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]]
noob
  • 774
  • 1
  • 10
  • 23
Dimitri
  • 1,924
  • 9
  • 43
  • 65

4 Answers4

2

Try this way

EntityUtils.toString(response.getEntity())
Biraj Zalavadia
  • 28,348
  • 10
  • 61
  • 77
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);
Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
0

Try Like this

String response = EntityUtils.toString(response.getEntity());
httpResponse.getEntity().consumeContent();
System.out.println("Cookie: "+ response);
vinay
  • 90
  • 7
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();

}
Haresh Chhelana
  • 24,720
  • 5
  • 57
  • 67
  • getting java.lang.ClassCastException: org.apache.http.message.BasicHttpResponse cannot be cast to org.apache.http.HttpEntity – Dimitri Nov 21 '13 at 10:26
  • 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 – Dimitri Nov 21 '13 at 12:41