Send authorization header with every request in webview using okhttp in android

Finally this will rectify the html rendering issue (Pardon me, I didn't notice this earlier).

change content-type in

return new WebResourceResponse(response.header("content-type", response.body().contentType().type()), // You can set something other as default content-type
                        response.header("content-encoding", "utf-8"),  // Again, you can set another encoding as default
                        response.body().byteStream());

to text/html , so the new code is

return new WebResourceResponse(response.header("text/html", response.body().contentType().type()), // You can set something other as default content-type
                    response.header("content-encoding", "utf-8"),  // Again, you can set another encoding as default
                    response.body().byteStream());

If my solution needs any modifications, feel free to edit. Always accept better solutions. Happy coding...And Thanks everyone #SO ready to help.


Sudheesh's answer was great, here is the updated version because shouldOverrideUrlLoading(WebView view, String url) was deprecated in API 21:

webView.setWebViewClient(new WebViewClient() {
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest webResourceRequest) {
                // Filter out any requests we not interested in
                if (webResourceRequest.getUrl().getHost() == null ||
                        !webResourceRequest.getUrl().getHost().equals(MyAPI.getServer().toHost())) {
                    return super.shouldInterceptRequest(view, webResourceRequest);
                }
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder().url(webResourceRequest.getUrl().toString())
                            .addHeader(HttpConnector.DefaultConnector().getAuthorizationHeaderKey(), HttpConnector.DefaultConnector().getAuthorizationHeaderValue())
                            .build();
                    Response response = okHttpClient.newCall(request).execute();
                    return new WebResourceResponse(response.header("text/html", response.body().contentType().type()), // You can set something other as default content-type
                            response.header("content-encoding", "utf-8"),  // Again, you can set another encoding as default
                            response.body().byteStream());
                } catch (ClientProtocolException e) {
                    //return null to tell WebView we failed to fetch it WebView should try again.
                    return null;
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        });