OkHTTPClient 将 cookie 传递给 Webview

OkHTTPClient pass cookies to Webview

我正在通过 OKHttpClient post 以用户身份登录,我想与 webview 共享 cookie。

这个 link 有帮助,但我不得不为我的 use-case 修改一些东西:http://artemzin.com/blog/use-okhttp-to-load-resources-for-webview/

以下代码有效:

webView = (WebView) findViewById(R.id.webView);    
WebSettings webSettings = webView.getSettings();

//enable javascript...
webSettings.setJavaScriptEnabled(true);

webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        progress.dismiss();
    }

    @SuppressWarnings("deprecation")
    @Override
    public WebResourceResponse shouldInterceptRequest(@NonNull WebView view, @NonNull String url) {
        return handleRequestViaOkHttp(url);
    }
});

webView.loadUrl("MY_URL.COM");

然后执行基本身份验证的代码 + 使用 OkHTTPClient 处理拦截 webview 请求。

@NonNull
private WebResourceResponse handleRequestViaOkHttp(@NonNull String url) {
    try {
        OkHttpClient client = new OkHttpClient();

        client.setAuthenticator(new Authenticator() {

            //for basic authorization...
            @Override
            public Request authenticate(Proxy proxy, com.squareup.okhttp.Response response) throws IOException {
                String credential = Credentials.basic(CommonResource.HEADER_USERNAME, CommonResource.HEADER_PASSWORD);
                return response.request().newBuilder().header("Authorization", credential).build();
            }

            @Override
            public Request authenticateProxy(Proxy proxy, com.squareup.okhttp.Response response) throws IOException {
                return null;
            }
        });

        final Call call = client.newCall(new Request.Builder()
            .url(url)
            .build()
        );

        final Response response = call.execute();

        return new WebResourceResponse("text/html", "UTF-8", response.body().byteStream());
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

在 OkHttp 3.0 中,您可以通过创建一个使用 webkit cookie 存储的 WebkitCookieManagerProxy 来使用类似于与 HttpURLConnection 共享的方法。改编自 .

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<String, List<String>> 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<String, List<String>> get(URI uri,
            Map<String, List<String>> 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<String, List<String>> res = new java.util.HashMap<String, List<String>>();

        // 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<Cookie> cookies) {
        HashMap<String, List<String>> generatedResponseHeaders = new HashMap<>();
        ArrayList<String> 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<Cookie> loadForRequest(HttpUrl url) {
        ArrayList<Cookie> cookieArrayList = new ArrayList<>();
        try {
            Map<String, List<String>> cookieList = get(url.uri(), new HashMap<String, List<String>>());
            // Format here looks like: "Cookie":["cookie1=val1;cookie2=val2;"]
            for (List<String> 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();

如果您只关心 OkHttp + WebView 那么它可以像这样简单:

class WebkitCookieManager (private val cookieManager: CookieManager) : CookieJar {

    override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
        cookies.forEach { cookie ->
            cookieManager.setCookie(url.toString(), cookie.toString())
        }
    }

    override fun loadForRequest(url: HttpUrl): List<Cookie> =
        when (val cookies = cookieManager.getCookie(url.toString())) {
            null -> emptyList()
            else -> cookies.split("; ").mapNotNull { Cookie.parse(url, it) }
        }
}

....


Usage:
 1. OkHttp
OkHttpClient.Builder().cookieJar(webkitCookieManager)

 2. WebView
CookieManager.getInstance().setCookie()

不用支持HttpURLConnection