Android - 在 webview 中登录后提取 cookie [英] Android - extracting cookies after login in webview

查看:30
本文介绍了Android - 在 webview 中登录后提取 cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序可以在 webview 中打开一个 url,然后用户必须通过 webview 登录到一个站点,并在登录后收到一个 cookie.登录后我在获取 cookie 时遇到问题.

I have an application that opens a url in a webview, the user must then login to a site through the webview and receives a cookie once logged in. I'm having problems getting cookies after login.

问题是,我可以使用 android.webkit.CookieManager 实现这一点,并将所有 cookie 输出到一个字符串中.

The problem is, I can achieve this using android.webkit.CookieManager, and output all cookies in a single string.

但是,我想使用 cookie 存储(如在 java.net.CookieStore 中)来实现它,所以我需要使用 java.net.CookieManager.

However, I want to achieve it using the a cookie store (as in java.net.CookieStore) so I need to be using java.net.CookieManager.

我在 WebViewClient 的 onPageFinished() 中使用以下代码.我知道问题在于打开一个新连接,我需要从当前页面获取内容.我很感激一些帮助,谢谢

I'm using the following code within the onPageFinished() of a WebViewClient. I know the issue is with opening a new connection, where I need to be getting the content from the current page. I'd appreciate some help, thanks

        @Override
        public void onPageFinished(WebView view, String url){

            Log.d(TAG, "Finished loading: " + url);

            CookieSyncManager syncManager = CookieSyncManager.createInstance(Main.this);
            syncManager.sync();

            CookieManager manager = new CookieManager();
            manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
            CookieHandler.setDefault(manager);

            try {
                URL blah = new URL(url);
                HttpURLConnection con = (HttpURLConnection) blah.openConnection();
                readStream(con.getInputStream()); // outputting html
            } 
            catch (Exception e) {
            }

            CookieStore cookieJar = manager.getCookieStore();
            List<HttpCookie> cookies = cookieJar.getCookies();

            for (HttpCookie cookie: cookies) {
                Log.d(TAG, "cookie name : "+cookie.getName().toString());
            }
        }

推荐答案

可以通过这种方式从 webview 中提取所有 cookie 当前 url 为字符串:

You can extract all cookies current url by this way from webview as string:

@Override
public void onPageFinished(WebView view, String url){
    String cookies = CookieManager.getInstance().getCookie(url);
    Log.d(TAG, "All the cookies in a string:" + cookies);
}

这篇关于Android - 在 webview 中登录后提取 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆