当前位置:  开发笔记 > 编程语言 > 正文

OkHTTPClient将cookie传递给Webview

如何解决《OkHTTPClient将cookie传递给Webview》经验,为你挑选了1个好方法。

我通过OKHttpClient帖子以用户身份登录,我想与webview共享cookie.



1> RyanCheu..:

使用OkHttp 3.0,您可以使用类似于与HttpURLConnection共享的方法,方法是创建一个使用webkit cookie存储的WebkitCookieManagerProxy.改编自HttpURLConnection(java.net.CookieManager)的Pass cookie到WebView(android.webkit.CookieManager).

public class WebkitCookieManagerProxy extends CookieManager implements CookieJar {
    private android.webkit.CookieManager webkitCookieManager;

    private static final String TAG = WebkitCookieManagerProxy.class.getSimpleName();

    public WebkitCookieManagerProxy() {
        this(null, null);
    }

    WebkitCookieManagerProxy(CookieStore store, CookiePolicy cookiePolicy) {
        super(null, cookiePolicy);
        this.webkitCookieManager = android.webkit.CookieManager.getInstance();
    }

    @Override
    public void put(URI uri, Map> responseHeaders)
            throws IOException {
        // make sure our args are valid
        if ((uri == null) || (responseHeaders == null))
            return;

        // save our url once
        String url = uri.toString();

        // go over the headers
        for (String headerKey : responseHeaders.keySet()) {
            // ignore headers which aren't cookie related
            if ((headerKey == null)
                    || !(headerKey.equalsIgnoreCase("Set-Cookie2") || headerKey
                            .equalsIgnoreCase("Set-Cookie")))
                continue;

            // process each of the headers
            for (String headerValue : responseHeaders.get(headerKey)) {
                webkitCookieManager.setCookie(url, headerValue);
            }
        }
    }

    @Override
    public Map> get(URI uri,
            Map> requestHeaders) throws IOException {
        // make sure our args are valid
        if ((uri == null) || (requestHeaders == null))
            throw new IllegalArgumentException("Argument is null");

        // save our url once
        String url = uri.toString();

        // prepare our response
        Map> res = new java.util.HashMap>();

        // get the cookie
        String cookie = webkitCookieManager.getCookie(url);

        // return it
        if (cookie != null) {
            res.put("Cookie", Arrays.asList(cookie));
        }

        return res;
    }

    @Override
    public CookieStore getCookieStore() {
        // we don't want anyone to work with this cookie store directly
        throw new UnsupportedOperationException();
    }

    @Override
    public void saveFromResponse(HttpUrl url, List cookies) {
        HashMap> generatedResponseHeaders = new HashMap<>();
        ArrayList cookiesList = new ArrayList<>();
        for(Cookie c: cookies) {
            // toString correctly generates a normal cookie string
            cookiesList.add(c.toString());
        }

        generatedResponseHeaders.put("Set-Cookie", cookiesList);
        try {
            put(url.uri(), generatedResponseHeaders);
        } catch (IOException e) {
            Log.e(TAG, "Error adding cookies through okhttp", e);
        }
    }

    @Override
    public List loadForRequest(HttpUrl url) {
        ArrayList cookieArrayList = new ArrayList<>();
        try {
            Map> cookieList = get(url.uri(), new HashMap>());
            // Format here looks like: "Cookie":["cookie1=val1;cookie2=val2;"]
            for (List ls : cookieList.values()) {
                for (String s: ls) {
                    String[] cookies = s.split(";");
                    for (String cookie : cookies) {
                        Cookie c = Cookie.parse(url, cookie);
                        cookieArrayList.add(c);
                    }
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "error making cookie!", e);
        }
        return cookieArrayList;
    }

}

然后在构建OkHttpClient时添加代理实例作为cookieJar.

client = new OkHttpClient.Builder().cookieJar(proxy).build();

推荐阅读
小白也坚强_177
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有