Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using WebView to display web page, but the server expects an authorization token with every request from my webview. Anybody know if this is possible ? I referred this post in #SO adding-header-to-all-request-with-retrofit-2. But I'm not able to get the result.

This is my code (bare with my coding standard, I'm a beginner)

    public class TableViewTest extends AppCompatActivity {

    ScrollView scrollView;
    WebView webView;
    SharedPreferences pref;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_table_view_test);

        //final ProgressDialog pd = ProgressDialog.show(this, "", "Loading...", true);


        webView = (WebView) findViewById(R.id.webView1Id)

        webView.setVerticalScrollBarEnabled(true);
        webView.setHorizontalScrollBarEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);

        webView.setWebViewClient(new WebViewClient() {

            @SuppressWarnings("deprecation")
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //return true load with system-default-browser or other browsers, false with your webView

                pref = getSharedPreferences("app", Context.MODE_PRIVATE);
                final String acToken = pref.getString("token", "DEFAULT");


                HashMap<String, String> headerMap = new HashMap<>();
                //put all headers in this header map
                headerMap.put("Authorization", acToken);


                view.loadUrl(url, headerMap);


                return false;
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }
        });

        webView.loadUrl("myurl");

    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        webView.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        webView.restoreState(savedInstanceState);
    }


    public WebViewClient getWebViewClientWithCustomHeader(){

        pref = getSharedPreferences("app", Context.MODE_PRIVATE);
        final String acToken = pref.getString("token", "DEFAULT");

        return new WebViewClient() {

            @SuppressWarnings("deprecation")
            public WebResourceResponse shouldInterceptRequest(WebView view, String url){
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder().url(url).addHeader("Authorization" , "Bearer " + acToken)
                            .build();

                    Response response = okHttpClient.newCall(request).execute();

                    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());


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

Any help is appreciated

EDIT

Now I am able to get the server response but in plain html, not rendering the css properly, don't know why.

Here is the new code,

    public class TableViewTest extends AppCompatActivity {

    ScrollView scrollView;
    WebView webView;
    SharedPreferences pref;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_table_view_test);

        //final ProgressDialog pd = ProgressDialog.show(this, "", "Loading...", true);

        String url = "myurl";
        pref = getSharedPreferences("app", Context.MODE_PRIVATE);


        webView = (WebView) findViewById(R.id.webView1Id);

        webView.setVerticalScrollBarEnabled(true);
        webView.setHorizontalScrollBarEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.setWebViewClient(wvc);

        webView.loadUrl("myurl");

    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        webView.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        webView.restoreState(savedInstanceState);
    }


    public WebViewClient wvc =  new WebViewClient() {

            @SuppressWarnings("deprecation")
            public WebResourceResponse shouldInterceptRequest(WebView view, String url){
                try {
                    final String acToken = pref.getString("token", "DEFAULT");

                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder().url(url).addHeader("Authorization" , "Bearer " + acToken)
                            .build();

                    Response response = okHttpClient.newCall(request).execute();

                    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());


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

And found this in stacktrace, nothing more in stacktrace

 E/DataReductionProxySettingListener: No DRP key due to exception:java.lang.ClassNotFoundException: com.android.webview.chromium.Drp
like image 685
Sudheesh R Avatar asked Jan 03 '17 09:01

Sudheesh R


Video Answer


2 Answers

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.

like image 96
Sudheesh R Avatar answered Sep 20 '22 13:09

Sudheesh R


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;
                }
            }
        });
like image 45
zkon Avatar answered Sep 20 '22 13:09

zkon