I’ve seen answers about how this should work with the old
DefaultHttpClient
but there’s not a good example forHttpURLConnection
I’m using HttpURLConnection to make requests to a web application. At the start of the my Android application, I use CookieHandler.setDefault(new CookieManager()) to automatically deal with the session cookies, and this is working fine.
At some point after the login, I want to show live pages from the web application to the user with a WebView instead of downloading data behind the scenes with HttpURLConnection. However, I want to use the same session I established earlier to prevent the user from having to login again.
How do I copy the cookies from java.net.CookieManager used by HttpURLConnection to android.webkit.CookieManager used by WebView so I can share the session?
As compared with
DefaultHttpClient, there are a few extra steps. The key difference is how to access the existing cookies inHTTPURLConnection:CookieHandler.getDefault()and cast the result tojava.net.CookieManager.getCookieStore()to access the cookie store.get()to access the list of cookies for the givenURI.Here’s a complete example: