Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a cookie along with HttpGet in Java

I am trying to send a cookie along with my HttpGet request, but everytime I try I havent been able to successfully send it. I also tried to modify the headers directly, here is my code:

DefaultHttpClient httpClient = new DefaultHttpClient();  

CookieStore store = new BasicCookieStore();
store.addCookie(MyCookieStorageClass.getCookie());
httpClient.setCookieStore(store);

HttpGet httpGet = new HttpGet("http://localhost/);     

try {
    // Execute HTTP Get Request  
    HttpResponse response = httpclient.execute(httpGet);  
    String responseData = ResponseHandler.getResponseBody(response);
} catch (IOException e) {
    e.printStackTrace();
}
like image 805
ninjasense Avatar asked Aug 01 '10 19:08

ninjasense


People also ask

How do I add a cookie to an HTTP response?

To add a new cookie, use HttpServletResponse. addCookie(Cookie). The Cookie is pretty much a key value pair taking a name and value as strings on construction.

How do I add a cookie to a Post request?

To add cookies to a request for authentication, use the header object that is passed to the get/sendRequest functions. Only the cookie name and value should be set this way. The other pieces of the cookie (domain, path, and so on) are set automatically based on the URL the request is made against.

Can you set-cookie in GET request?

Also I would say it is perfectly acceptable to change or set a cookie in response for the GET request because you just return some data.

What is Httpget Java?

The HttpGet class represents the HTTPGET request which retrieves the information of the given server using a URI. Create a HTTP GET request by instantiating this class. The constructor of this class accepts a String value representing the URI.


1 Answers

This is actually the correct implementation for the HttpClient 4.0.1, I had just had not been getting the correct cookie.

like image 194
ninjasense Avatar answered Oct 13 '22 00:10

ninjasense