Disable/Ignore Cookies with Httpclient

How can I disable/ignore default cookie handling of httpclient. I want to do it manually. I want to set a pre-defined cookie header for all http requests.

4 Answers

The latest httpclient (4.5.1) has a method called "disableCookieManagement", and it appears this just disables the internal cookie management, not the ability to send or receive cookies, and is working for me-

()

Set httpclient.setCookieStore(cookieStore); before you execute your HttpClient

3

Force to setup the HttpContext before executing the request:

private HttpClientContext httpContext = new HttpClientContext();
httpContext.setCookieStore(new BasicCookieStore());

The setCookieStore will create an empty cookie store to replace the default cookie store of http connection.

After that we can execute the http method:

org.apache.http.client.HttpClient.execute(HttpUriRequest, HttpContext)

Also we can reuse the cookie store (hold the BasicCookieStore) to keep the connection alive.

I could not find a way to disable/ignore cookie handling by DefaultHttpClient in Andoroid(I should have explored more into Android source code but have a time limitation). But I resolved it by removing all cookies before doing httpClient.execute() like this -

((AbstractHttpClient) myDefaultHttpClient).getCookieStore().clear();

This removes all the cookies stored by the defaultHttpClient and then you can manually handle(add/delete) cookies using -

myHttpPost.setHeader("Cookie", myCookie);

Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest