问题描述
我见过这个应该如何与旧的答案 DefaultHttpClient
但有没有一个很好的例子,<$c$c>HttpURLConnection
我用的HttpURLConnection
来发出请求到Web应用程序。在我的Android应用程序的开始,我用 CookieHandler.setDefault(新CookieManager())
来自动处理会话cookie,这是工作的罚款。
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.
在登录后的某个时刻,我想告诉从Web应用程序活页,使用的WebView用户
,而不是下载的幕后数据的HttpURLConnection
。不过,我想用同一个会话我早些时候成立,prevent用户不必重新登录。
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.
我如何从 java.net.CookieManager
复制饼干使用的HttpURLConnection
到 android.webkit.CookieManager
使用的WebView
这样我就可以共享会话?
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?
推荐答案
与 DefaultHttpClient
相比,有一些额外的步骤。关键的区别是如何访问现有的cookie的的HttpURLConnection
:
As compared with DefaultHttpClient
, there are a few extra steps. The key difference is how to access the existing cookies in HTTPURLConnection
:
- 呼叫
CookieHandler.getDefault()
并把结果转换java.net.CookieManager
。 - 通过cookie管理器,通话
getCookieStore()
访问cookie存储区。 - 通过cookie存储,调用
的get()
来访问cookie的列表中给定的URI
。
- 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
...
}
这篇关于从HttpURLConnection的(java.net.CookieManager)来的WebView传递饼干(android.webkit.CookieManager)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!