49

I am using HttpClient 4.1.2

HttpGet httpget = new HttpGet(uri); 
HttpResponse response = httpClient.execute(httpget);

So, how can I get the cookie values?

skaffman
  • 398,947
  • 96
  • 818
  • 769
coffee
  • 3,048
  • 4
  • 32
  • 46

5 Answers5

62

Not sure why the accepted answer describes a method getCookieStore() that does not exist. That is incorrect.

You must create a cookie store beforehand, then build the client using that cookie store. Then you can later refer to this cookie store to get a list of cookies.

/* init client */
HttpClient http = null;
CookieStore httpCookieStore = new BasicCookieStore();
HttpClientBuilder builder = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore);
http = builder.build();

/* do stuff */
HttpGet httpRequest = new HttpGet("http://stackoverflow.com/");
HttpResponse httpResponse = null;
try {httpResponse = http.execute(httpRequest);} catch (Throwable error) {throw new RuntimeException(error);}

/* check cookies */
httpCookieStore.getCookies();
Alex
  • 5,909
  • 2
  • 35
  • 25
  • 4
    The accepted answer worked for previous version of v4. This approach works with the latest one. – Peter Nov 19 '15 at 09:00
  • 2
    Yes, this should be the accepted answer. I am just migrating an old httpclient (3.x to 4.3) to the new one and this answer really helps. – рüффп Feb 04 '16 at 13:46
  • 3
    You can do even simplier : `CloseableHttpClient httpclient = httpClients.custom().setDefaultCookieStore(cookies).build();` – Hugodby May 29 '17 at 15:24
  • how it will work in case of few requests and few different cookies with same name? – Mikhail Ionkin Jul 26 '22 at 09:29
  • The cookies in the cookie store have all the details you would expect, like name, value, domain, path, date, et al. It keeps track of all cookies received from the HTTP client, however many requests are made. – Alex Aug 08 '22 at 15:37
14

Yet another to get other people started, seeing non-existent methods scratching their heads...

import org.apache.http.Header;
import org.apache.http.HttpResponse;

Header[] headers = httpResponse.getHeaders("Set-Cookie");
for (Header h : headers) {
    System.out.println(h.getValue().toString());  
}

This will print the values of the cookies. The server response can have several Set-Cookie header fields, so you need to retrieve an array of Headers

Kovács Imre
  • 715
  • 2
  • 7
  • 17
8

Please Note: The first link points to something that used to work in HttpClient V3. Find V4-related info below.

This should answer your question

http://www.java2s.com/Code/Java/Apache-Common/GetCookievalueandsetcookievalue.htm

The following is relevant for V4:

...in addition, the javadocs should contain more information on cookie handling

http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/index.html

and here is a tutorial for httpclient v4:

http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html

And here is some pseudo-code that helps (I hope, it's based only on docs):

HttpClient httpClient = new DefaultHttpClient();
// execute get/post/put or whatever
httpClient.doGetPostPutOrWhatever();
// get cookieStore
CookieStore cookieStore = httpClient.getCookieStore();
// get Cookies
List<Cookie> cookies = cookieStore.getCookies();
// process...

Please make sure you read the javadocs for ResponseProcessCookies and AbstractHttpClient.

mkro
  • 1,902
  • 14
  • 15
  • ok, got it: please have a look at the class ResponseProcessCookies for more details. HttpClientv4 appears to use it (by default) to populate the cookie store. You can access it from AbstractHttpClient.getCookieStore – mkro Jan 04 '12 at 22:01
  • 34
    This is the problem. I can't find the method `httpClient.getCookieStore();` – coffee Jan 05 '12 at 12:21
  • Sorry if my doubt is too simple, but how can I call this method ? – coffee Jan 05 '12 at 12:32
  • Given that you are using v4.1.2, this method should be available in DefaultHttpClient and other extensions of the abstract base class. You use new HttpGet instead. Can you try the pseudo code that i submitted and see what you get? – mkro Jan 06 '12 at 20:18
  • 2
    org.apache.http.impl.client.AbstractHttpClient httpClient = new org.apache.http.impl.client.DefaultHttpClient() The cast seems to allow you to get the cookie store – Matt Broekhuis Nov 28 '13 at 08:36
  • @coffee Sorry to necro - but HttpClient itself doesn't have have the getCookieStore() method. So I suspect you are using something like : HttpClient httpClient = new DefaultHttpClient() which will not expose the method you are looking for. As mentioned above use something like DefaultHttpClient httpClient = new DefaultHttpClient(); and getCookieStore() is there for you. – zorkle Sep 01 '14 at 20:21
  • Pointing to the doc is correct however you're using the wrong implementation: DefaultHttpClient is deprecated and the way you show relates to the previous version of Apache HttpClient library (<4). Alex's answer is the new way to do. – рüффп Feb 04 '16 at 13:49
  • Ye maybe `DefaultHttpClient` has the required method but what if we want to stay implementation indepenedent? Creating own CookieStore or at least leaving a reference to the default one is the way to go. – Antoniossss Aug 17 '16 at 08:51
  • 1
    This deprecated is outdated, please see @Alex answer below or look at the documentation : http://hc.apache.org/httpcomponents-client-ga/tutorial/html/statemgmt.html#d5e576 – Hugodby May 29 '17 at 15:27
6

Based on the example in the initial question, the way to access the CookieStore after executing an HTTP request, is by using the HttpContext execution state object.

HttpContext will reference a cookie store (new if no CookieStore was specified in the HttpClientBuilder) after a request is executed.

HttpClientContext context = new HttpClientContext();
CloseableHttpResponse response = httpClient.execute(request, context);
CookieStore cookieStore = context.getCookieStore();

This applies on httpcomponents-client:4.3+ when the ClosableHttpClient was introduced.

1

As Matt Broekhuis answered in a comment on this answer above, you can use DefaultHttpClient.getCookieStore()

Note, that at the time that I answered my server was limited to httpclient-4.2.5. DefaultHttpClient is now deprecated as of 4.3. I'm going to leave this answer here because others might find themselves in the same situation and the original poster specified they were using 4.1.2.

import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.IOException;
import java.util.List;

public class So8733758 {

  public static void main(String... args) throws IOException {
    final HttpUriRequest request = new HttpGet("http://stackoverflow.com");
    final DefaultHttpClient http = new DefaultHttpClient();
    http.execute(request);
    final List<Cookie> cookies = http.getCookieStore().getCookies();
    System.out.println(cookies);
  }
}

which outputs

[[version: 0][name: __cfduid][value: de2dfa8314f565701cf7b3895206f04d81457380383][domain: .stackoverflow.com][path: /][expiry: Tue Mar 07 11:53:03 PST 2017], [version: 0][name: prov][value: eeee9738-c50b-44f6-a8aa-b54966db1a88][domain: .stackoverflow.com][path: /][expiry: Thu Dec 31 16:00:00 PST 2054]]
Community
  • 1
  • 1
Kirby
  • 15,127
  • 10
  • 89
  • 104