在 Android 中为 webView 设置 cookie

发布于 2024-11-02 17:01:08 字数 1276 浏览 1 评论 0原文

检查用户名或密码是否正确时,我从服务器收到 HttpResponse。 当我在 webview 中加载 url 时,我希望 webView 具有 cookie(我通过 postData()< 得到的答案/code> 存储在 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;
}

我 loadUrl 为:

webView.loadUrl("http://a_page.com/getpage.aspx?p=home");

我想我并没有真正管理 cookie,而且我不知道该怎么做。 有什么建议或解决方案吗?

I'm getting a HttpResponse from a server when checking if a username or password is correct.
When I load the url in a webview I want the webView to have the cookie (the answer I get with postData() stored in the webView.
I want the webView to pickup the cookie and load the url with that cookie stored in the webview.

I'm getting the response through.

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;
}

And I loadUrl with:

webView.loadUrl("http://a_page.com/getpage.aspx?p=home");

I guess I'm not really managing a cookie and I have no idea how to do so.
Any suggestions or solutions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

笑忘罢 2024-11-09 17:01:08

这真的很简单。

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

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

It's quite simple really.

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

where cookieString is formatted the same as a more traditional Set-Cookie HTTP header, and baseUrl is the site the cookie should belong to.

小傻瓜 2024-11-09 17:01:08

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

  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,则不能保证 cookie 已被写入。为了防止意外和不稳定的行为,请使用 CookieManager#setCookie(String url, String value, ValueCallbackcallback) (link) 并开始加载 url将调用回调。

我希望我的两分钱可以节省一些人的时间,这样您就不必像我一样面临同样的问题。

Couple of comments which I found out from my experience and gave me headaches:

  1. http and https urls are different. Setting a cookie for http://www.example.com is different than setting a cookie for https://www.example.com
  2. A slash in the end of the url can also make a difference. In my case https://www.example.com/ works but https://www.example.com does not work.
  3. CookieManager.getInstance().setCookie is performing an asynchronous operation. So, if you load a url right away after you set it, it is not guaranteed that the cookies will have already been written. To prevent unexpected and unstable behaviours, use the CookieManager#setCookie(String url, String value, ValueCallback callback) (link) and start loading the url after the callback will be called.

I hope my two cents save some time from some people so you won't have to face the same problems like I did.

爱她像谁 2024-11-09 17:01:08

如果你有很少的带有 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")

You should use it with some loop if you have few items with cookies (like in my case):

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

You can't use it like:

CookieManager.getInstance().setCookie("http://someHost.com", "key1=someValue1;key2=someValue2;key3=someValue3")
缘字诀 2024-11-09 17:01:08

您可能想看看我如何设置 webview cookie:

Android WebView Cookie 问题

在我的回答中,您可以看到我是如何处理这个问题的,如下所示:

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

You may want to take a look of how I am setting the a webview cookie at :

Android WebView Cookie Problem

Where in my answer you could see how I'm handling this like:

val cookieManager = CookieManager.getInstance()
cookieManager.acceptCookie()
cookieManager.setCookie(domain,"$cookieKey=$cookieValue")
cookieManager.setAcceptThirdPartyCookies(view.webViewTest,true)
呆橘 2024-11-09 17:01:08

只是想用另一种方式来完成这件事。并不是说这是最好的,但这是一种方法。您也可以使用 JavaScript 来设置 cookie。只需在 WebViewClient 中重写 onPageFinished

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。如果有人知道如何解决这个问题,请发表评论。

Just wanna throw another way how this can be done. Not saying it is the best, but it is a way. You can use JavaScript to set cookies as well. Just override onPageFinished in WebViewClient

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)
                }
        }
}

One thing with this approach: you will have to reload the webView. If anyone knows how to fix that, please comment.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文