Мне нужно добавить заголовки http-запросов к любым запросам моего WebView, и я узнал этот код:
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
try {
OkHttpClient httpClient = new OkHttpClient();
com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder()
.url(url.trim())
.addHeader("<your-custom-header-name>", "<your-custom-header-value>")
.build();
com.squareup.okhttp.Response response = httpClient.newCall(request).execute();
return new WebResourceResponse(
response.header("content-type", response.body().contentType().type()), // You can set something other as default content-type
response.header("content-encoding", "utf-8"), // Again, you can set another encoding as default
response.body().byteStream()
);
} catch (ClientProtocolException e) {
//return null to tell WebView we failed to fetch it WebView should try again.
return null;
} catch (IOException e) {
//return null to tell WebView we failed to fetch it WebView should try again.
return null;
}
}
в этом посте: Добавление пользовательских заголовков к запросам ресурсов WebView - android
Моя проблема в том, что этот код пытается загрузить файл (мобильный показывает тост "Загрузка файла"), и он не загружается вместо загрузки html-страницы.
ОБНОВЛЕНИЕ
Я попытался вернуть null, если ресурс - это изображение, CSS, Javascript или что-то подобное (таким образом, веб-просмотр продолжается с нормальным поведением), но все же у меня есть тост «Файл Doanloading».