I'm trying to intercept every request sent by a WebView and modify the headers before executing the request. There are a bunch of examples of how to do this (like this one), but I can't quite get it to work. Pages are able to load fine, but all of the requests look something like this in the Chrome debugger; they warn that "Provisional headers are shown" and none of my headers are present.
Here is the relevant section of my code:
public class MyWebView extends WebView {
public MyWebView(Context context) {
super(context);
setWebViewClient(new MyWebViewClient());
}
private class MyWebViewClient extends WebViewClient {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
WebResourceResponse response = null;
try {
URL url = new URL(request.getUrl().toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(request.getMethod());
conn.setRequestProperty("test-header", "test-value");
InputStream data;
if (conn.getResponseCode() / 100 == 2) {
data = conn.getInputStream();
}
else {
data = conn.getErrorStream();
}
response = new WebResourceResponse("text/html", "UTF-8", data);
}
catch (IOException e) {
}
return response;
}
}
}
I also tried using OkHttp instead, but got the same results. Anyone able to get this working?