Tag Archives: HttpURLConnection

URLConnection with Cookies

Updated on 25/11/2015: You should take a note about cookie with redirect-request. By default HttpURLConnection will take care about it automatically. You set your wide-system CookieManager, you pass a cookie to request, everything is OK.

But in case you have no default CookieManager and you do request without Cookie in header, you will get the problem. There’s no cookie was returned with response. This is because of HttpURLConnection set/get cookie for each request/response through the wide-system CookieManager instance. Let see bellow flow:

  1. Client sends a request without Cookie in header.
  2. Server returns a response which has code 301, new Localtion and Cookie inside header.
  3. HttpURLConnection looks at the header of response. It takes the Cookie then checks the global CookieManager instance. The instance if NULL then no cookie was saved.
  4. HttpURLConnection automatically make other request due to the Location. But because of no instance of CookieManager is available, then this request has no Cookie header too.
  5. Server receives the redirect request and sees no Cookie in header. It understands that no need to use Cookie mechanism. So it returns a request which has no Cookie.

To solve this problem, we can disable automatically process redirection by method setInstanceFollowRedirects(boolean) and do it by yourself. Notice that at step 3, you will extract Cookie header and set it to step 4 manually by setRequestProperty(String, String) and getHeaderField(String key).

As we know that Android 6.0 releases doesn’t support Apache HTTP client anymore. Instead of this, we will use the HttpURLConnection class. This API is more efficient, and in fact there are many interesting things to do with it. However today I only start with managing cookies. In that I will just focus on customize your own CookieStore. Continue reading