此问题在此处已有答案:
Why does Android WebView sporadically not sending my session cookie?(16个答案)
1年前关闭。
我在检查用户名或密码是否正确时从服务器获得HttpResponse
。当我在webview
中加载url
时,我希望webView
具有cookie(我通过postData()
获得的答案存储在webView
中。我希望webView拾取cookie并加载具有存储在webview中的cookie的URL。
我正在回复。
public HttpResponse postData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://example.com/login.aspx");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("txtUsername", "user"));
nameValuePairs.add(new BasicNameValuePair("txtPassword", "123"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String responseAsText = EntityUtils.toString(response.getEntity());
Log.v(TAG , "Response from req: " + responseAsText);
return responseAsText;
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
我用以下代码加载Url:
webView.loadUrl("http://a_page.com/getpage.aspx?p=home");
我想我并不是真的在管理一个cookie,我也不知道该怎么做。有什么建议或解决方案吗?
5条答案
按热度按时间yuvru6vn1#
其实很简单。
其中
cookieString
的格式与更传统的Set-Cookie
HTTP头相同,baseUrl
是cookie应属于的站点。gupuwyp22#
我从我的经历中发现了一些让我头疼的评论:
http
和https
的url不同。为http://www.example.com
设置cookie与为https://www.example.com
设置cookie不同https://www.example.com/
可以工作,但https://www.example.com
不能工作。CookieManager.getInstance().setCookie
正在执行异步操作。因此,如果在设置url后立即加载该url,则无法保证已写入Cookie。为防止出现意外和不稳定的行为,请使用CookieManager#setCookie(String url,String value,ValueCallback callback)(link)并在调用回调后开始加载url。我希望我的两分钱能为一些人节省一些时间,这样你就不必像我一样面对同样的问题了。
v9tzhpje3#
您可能想看看我是如何设置一个webview cookie:
Android WebView Cookie问题
在我的回答中,你可以看到我是如何处理这个问题的:
luaexgnf4#
如果你有一些带有cookie的条目(就像我的例子),你应该用循环来使用它:
你不能这样使用它:
gj3fmq9x5#
只是想抛出另一种方法可以做到这一点。不是说这是最好的,但它是一种方法。你可以使用JavaScript来设置cookie以及。只是覆盖
onPageFinished
在WebViewClient
这种方法有一点:您将不得不重新加载webView。如果有人知道如何修复,请发表评论。