在Android中为webView设置cookie [重复]

cbjzeqam  于 2023-03-11  发布在  Android
关注(0)|答案(5)|浏览(316)

此问题在此处已有答案

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,我也不知道该怎么做。有什么建议或解决方案吗?

yuvru6vn

yuvru6vn1#

其实很简单。

String cookieString = "cookie_name=cookie_value; path=/";
CookieManager.getInstance().setCookie(baseUrl, cookieString);

其中cookieString的格式与更传统的Set-Cookie HTTP头相同,baseUrl是cookie应属于的站点。

gupuwyp2

gupuwyp22#

我从我的经历中发现了一些让我头疼的评论:

  1. httphttps的url不同。为http://www.example.com设置cookie与为https://www.example.com设置cookie不同
  2. url末尾的斜线也会产生不同的效果。在我的例子中,https://www.example.com/可以工作,但https://www.example.com不能工作。
  3. CookieManager.getInstance().setCookie正在执行异步操作。因此,如果在设置url后立即加载该url,则无法保证已写入Cookie。为防止出现意外和不稳定的行为,请使用CookieManager#setCookie(String url,String value,ValueCallback callback)(link)并在调用回调后开始加载url。
    我希望我的两分钱能为一些人节省一些时间,这样你就不必像我一样面对同样的问题了。
v9tzhpje

v9tzhpje3#

您可能想看看我是如何设置一个webview cookie:
Android WebView Cookie问题
在我的回答中,你可以看到我是如何处理这个问题的:

val cookieManager = CookieManager.getInstance()
cookieManager.acceptCookie()
cookieManager.setCookie(domain,"$cookieKey=$cookieValue")
cookieManager.setAcceptThirdPartyCookies(view.webViewTest,true)
luaexgnf

luaexgnf4#

如果你有一些带有cookie的条目(就像我的例子),你应该用循环来使用它:

val cookiesList = listOf("key1=someValue1", "key2=someValue2", "key3=someValue3")
cookiesList.forEach { item ->
 CookieManager.getInstance().setCookie("http://someHost.com", item)
}

不能这样使用它:

CookieManager.getInstance().setCookie("http://someHost.com", "key1=someValue1;key2=someValue2;key3=someValue3")
gj3fmq9x

gj3fmq9x5#

只是想抛出另一种方法可以做到这一点。不是说这是最好的,但它是一种方法。你可以使用JavaScript来设置cookie以及。只是覆盖onPageFinishedWebViewClient

new WebViewClient() {

        override fun onPageFinished(view: WebView, url: String) {

                val javascript = """document.cookie = "key=$value""""

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    view.evaluateJavascript(javascript) { s -> Timber.d("Inject: %s", s) }
                } else {
                    view.loadUrl("javascript:" + javascript, null)
                }
        }
}

这种方法有一点:您将不得不重新加载webView。如果有人知道如何修复,请发表评论。

相关问题