5

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

Chris004
  • 91
  • 1
  • 1
  • 5
  • 2
    please refer to this post : [Add custom headers to WebView resource requests](http://stackoverflow.com/questions/7610790/add-custom-headers-to-webview-resource-requests-android) – Zhang Xiang Oct 09 '16 at 02:17

2 Answers2

4

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.

Manikanta
  • 3,421
  • 4
  • 30
  • 51
-1

You can put this setting to your web setting, every request from webview will be using this User-Agent header.

webview.getSettings().setUserAgentString("user-agent-string");