Issue
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?
Solution
As compared with DefaultHttpClient
, there are a few extra steps. The key difference is how to access the existing cookies in HTTPURLConnection
:
- Call
CookieHandler.getDefault()
and cast the result tojava.net.CookieManager
. - With the cookie manager, call
getCookieStore()
to access the cookie store. - With the cookie store, call
get()
to access the list of cookies for the givenURI
.
Here's a complete example:
@Override
protected void onCreate(Bundle savedInstanceState) {
// Get cookie manager for WebView
// This must occur before setContentView() instantiates your WebView
android.webkit.CookieSyncManager webCookieSync =
CookieSyncManager.createInstance(this);
android.webkit.CookieManager webCookieManager =
CookieManager.getInstance();
webCookieManager.setAcceptCookie(true);
// Get cookie manager for HttpURLConnection
java.net.CookieStore rawCookieStore = ((java.net.CookieManager)
CookieHandler.getDefault()).getCookieStore();
// Construct URI
java.net.URI baseUri = null;
try {
baseUri = new URI("http://www.example.com");
} catch (URISyntaxException e) {
// Handle invalid URI
...
}
// Copy cookies from HttpURLConnection to WebView
List<HttpCookie> cookies = rawCookieStore.get(baseUri);
String url = baseUri.toString();
for (HttpCookie cookie : cookies) {
String setCookie = new StringBuilder(cookie.toString())
.append("; domain=").append(cookie.getDomain())
.append("; path=").append(cookie.getPath())
.toString();
webCookieManager.setCookie(url, setCookie);
}
// Continue with onCreate
...
}
Answered By - quietmint
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.