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();
}
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.
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.
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.
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.
This is actually the correct implementation for the HttpClient 4.0.1, I had just had not been getting the correct cookie.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With