Tim Nuwin Tim Nuwin - 1 year ago 399
Android Question

OkHTTPClient pass cookies to Webview

I am logging in as a user via an OKHttpClient post and I would like to share the cookies with the webview.

Answer Source

This link helped but I had to modify a few things for my use-case: http://artemzin.com/blog/use-okhttp-to-load-resources-for-webview/

The below code works:

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

//enable javascript...

webView.setWebViewClient(new WebViewClient() {
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

    public WebResourceResponse shouldInterceptRequest(@NonNull WebView view, @NonNull String url) {
        return handleRequestViaOkHttp(url);


Then the code that does the basic auth + handles intercepting the webview request using OkHTTPClient.

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

        client.setAuthenticator(new Authenticator() {

            //for basic authorization...
            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();

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

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

        final Response response = call.execute();

        return new WebResourceResponse("text/html", "UTF-8", response.body().byteStream());
    } catch (Exception e) {
        return null;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download