Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Webview Add header to HTTP request [duplicate]

Tags:

android

I would like to to add headers to HTTP requests in ANDROID WEBVIEW using Android 4.0 and greater. How do you do this?

like image 367
Chris004 Avatar asked Oct 18 '22 00:10

Chris004


1 Answers

Hey i have had enough time spent on figuring out this(especially cookies) here is how i solved.

So For your question on how to set header:

1.in Oncreate()

final WebSettings  settings = wv_payment.getSettings();

        settings.setJavaScriptEnabled(true);
        settings.setDisplayZoomControls(false);
        settings.setAppCacheEnabled(true);
        settings.setLoadsImagesAutomatically(true);
        settings.setBuiltInZoomControls(false);
        settings.setPluginState(WebSettings.PluginState.ON);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

The above ones are to enable javascript etc..

To add headers you need to set webViewclient to your webview as follows(here my website needs a basic authentication in header so i'm adding it as follows)

wv_payment.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    String credentials = "username" + ":" + "password";

                    final String basic =
                            "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

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


                    view.loadUrl(url, headerMap);
                    return true;
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
    //dismissing loading progress
                    AppUtils.dismissProgressDialog(progressDialog);
                }

                @Override
                public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
                //here goes your url authentications if any
                    handler.proceed("username", "password");
                }
            });

Comment below if you have any doubts.

like image 116
Manikanta Avatar answered Nov 15 '22 05:11

Manikanta