How can I get the cookies from HttpClient?
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();
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 Header
s
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.
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.