Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the cookies from HttpClient?

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?

like image 423
coffee Avatar asked Jan 04 '12 20:01

coffee


People also ask

How do I send a cookie request in header?

To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons.

What is closeable HttpClient?

CloseableHttpClient is the base class of the httpclient library, the one all implementations use. Other subclasses are for the most part deprecated. The HttpClient is an interface for this class and other classes. You should then use the CloseableHttpClient in your code, and create it using the HttpClientBuilder .

How do you add a cookie to an HTTP request in Java?

Use BasicClientCookie. setDomain() to set the cookie domain. To understand this, assume your http-client lib as browser interacting with a web site. The browser stores cookies from many sites, but while making a request to a particular site it sends only those cookies which it has received from that particular site.


2 Answers

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(); 
like image 171
Alex Avatar answered Sep 25 '22 02:09

Alex


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

like image 23
Kovács Imre Avatar answered Sep 24 '22 02:09

Kovács Imre