Tim Nuwin Tim Nuwin - 4 months ago 103
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

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...
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");

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

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