I am currently using this code to add a custom header to android WebView
Map<String, String> extraHeaders = new HashMap<String, String>();
extraHeaders.put("example", "header");
webView.loadUrl(url, extraHeader);
Above code is working but only on the main page. So if I write this code echo $_SERVER['example']
it prints header
. But there is an iframe
in the loaded URL which shows an undefined error when I try the same code. Is there any way I can fix this?
So what I want to do is add custom header not only to the main loaded URL but also on the iframe
of the loaded page.
This worked for me:
mWebView.setWebViewClient(new MyWebViewClient(token));
in MyWebViewClient
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
try {
OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url.trim())
.addHeader("token", mToken) //add headers
.build();
Response response = httpClient.newCall(request).execute();
return new WebResourceResponse(
getMimeType(url), // set content-type
response.header("content-encoding", "utf-8"),
response.body().byteStream()
);
} catch (IOException e) {
return null;
}
}
//get mime type by url
public String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
if (extension.equals("js")) {
return "text/javascript";
}
else if (extension.equals("woff")) {
return "application/font-woff";
}
else if (extension.equals("woff2")) {
return "application/font-woff2";
}
else if (extension.equals("ttf")) {
return "application/x-font-ttf";
}
else if (extension.equals("eot")) {
return "application/vnd.ms-fontobject";
}
else if (extension.equals("svg")) {
return "image/svg+xml";
}
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;
}
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");
No, that is not possible with Android WebView itself. You have to work around either in your page code, or in your app's code, or on the server.
For fixing this on the page's side, you can use XMLHttpRequest
for loading subresources. But for that you will have basically to construct the page on the fly.
On the app's side, you can use WebViewClient.shouldInterceptRequest
, to intercept all the network requests. You are not allowed to just modify the provided request, instead, you will need to make a new request yourself, but there you will be able to set any headers you want. See this example: Android WebViewClient url redirection (Android URL loading system)
On the server side, you can look into Referer
header of subresources, which must contain the url of the page that has requested it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With