我需要修改android webView请求的请求标头。所以,我在方法 shouldInterceptRequest 中添加以下代码。 这是我的代码。
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
try {
String mUrl = request.getUrl().toString();
OkHttpClient httpClient = new OkHttpClient();
Request mRequest = new Request.Builder()
.url(request.getUrl().toString())
.addHeader("token", UserHelper.getToken()) //add headers
.build();
Response response = httpClient.newCall(mRequest).execute();
return new WebResourceResponse(
getMimeType(request.getUrl().toString()), // set content-type
response.header("content-encoding", "utf-8"),
response.body().byteStream()
);
} catch (Exception e) {
return super.shouldInterceptRequest(view, request);
}
return super.shouldInterceptRequest(view, request);
}
实际上,它有效,所有请求都带有新标头。但是,因为我构造了新请求,原始请求方法/正文丢失了。我不知道如何保留WebResourceRequest的原始方法和主体。