Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I retrieve the cookies from a POST request?

I can send POST requests using org.apache.http.clien.HttpClient and get the HTTP response. But I don´t get the HTML content when logged in because my PHP script requires a cookie. So, how can I read the cookie of the POST request response and send it back using a GET request after the POST request?

    HttpClient httpClient = new DefaultHttpClient();

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
    nameValuePairs.add(new BasicNameValuePair("username", "user"));  
    nameValuePairs.add(new BasicNameValuePair("password", "passwd"));  

    HttpPost httpPost = new HttpPost("http://localhost/index.php");
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    HttpResponse httpResponse = httpClient.execute(httpPost);

    BufferedInputStream bis = new BufferedInputStream(httpResponse.getEntity().getContent()); // Just gets the HTML content, not the cookies
like image 480
Rox Avatar asked Apr 28 '12 15:04

Rox


2 Answers

the cookies are a standard header, so you can get it from

 httpResponse.getHeader("Cookie")

If you as calling the server from the same application, you can let the httpclient maintain cookie state rather. Don't create a new instance every-time and it should work.

like image 151
Bruce Lowe Avatar answered Sep 23 '22 19:09

Bruce Lowe


If you use the same HTTPClient instance and your server is sending the right headers, it should be handled automatically.

See http://hc.apache.org/httpclient-3.x/cookies.html

like image 25
dfb Avatar answered Sep 26 '22 19:09

dfb