I would like to to add headers to HTTP requests in ANDROID WEBVIEW using Android 4.0 and greater. How do you do this?
Asked
Active
Viewed 1.4k times
2 Answers
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");

Rahmat Rasyidi Hakim
- 29
- 2