I'd like to make an http request to a remote server while properly handling cookies (eg. storing cookies sent by the server, and sending those cookies when I make subsequent requests). It'd be nice to preserve any and all cookies, but really the only one I care about is the session cookie.
With java.net, it appears that the preferred way to do this is using java.net.CookieHandler (abstract base class) and java.net.CookieManager (concrete implementation). Android has java.net.CookieHandler, but it does not seem to have java.net.CookieManager.
I could code it all by hand by inspecting http headers, but it seems like there must be an easier way.
What is the proper way to make http requests on Android while preserving cookies?
It turns out that Google Android ships with Apache HttpClient 4.0, and I was able to figure out how to do it using the "Form based logon" example in the HttpClient docs:
http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/httpclient/src/examples/org/apache/http/examples/client/ClientFormLogin.java
A cookie is just another HTTP header. You can always set it while making a HTTP call with the apache library or with HTTPUrlConnection. Either way you should be able to read and set HTTP cookies in this fashion.
You can read this article for more information.
I can share my peace of code to demonstrate how easy you can make it.
Since Apache library is deprecated, for those who want to use
HttpURLConncetion
, I wrote this class to send Get and Post Request with the help of this answer:I do not work with google android but I think you'll find it's not that hard to get this working. If you read the relevant bit of the java tutorial you'll see that a registered cookiehandler gets callbacks from the HTTP code.
So if there is no default (have you checked if
CookieHandler.getDefault()
really is null?) then you can simply extend CookieHandler, implement put/get and make it work pretty much automatically. Be sure to consider concurrent access and the like if you go that route.edit: Obviously you'd have to set an instance of your custom implementation as the default handler through
CookieHandler.setDefault()
to receive the callbacks. Forgot to mention that.