How can I retrieve the cookies from a POST request?

33,082

Solution 1

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.

Solution 2

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

Share:
33,082
Rox
Author by

Rox

Updated on April 29, 2020

Comments

  • Rox
    Rox almost 4 years

    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
    
  • JasonH
    JasonH almost 7 years
    String cookie = httpResponse.getFirstHeader("Cookie").getValue();
  • BxlSofty
    BxlSofty about 5 years
    If you need to decode the cookies sent by the server it's httpResponse.getHeaders("Set-Cookie")