nterceptRequest中向WebResourceRequ

nterceptRequest中向WebResourceRequ

本文介绍了通过在ShouldInterceptRequest中向WebResourceRequest的标头添加标头来向WebView添加自定义标头不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要向WebView中加载的页面添加自定义标头,但是它不起作用,未设置标头:

I need to add a custom header to a page loading in WebView, but it doesn't work, header is not set:

@Override
public WebResourceResponse shouldInterceptRequest (WebView view,  WebResourceRequest request)
{
    request.getRequestHeaders().add("MyHeader","MyValue");
    return super.shouldInterceptRequest(view, request);
}

我在这里做错了什么?我在Android 5上运行.

What I am doing wrong here? I'm running on Android 5.

我在SO上看到了很多答案,说您必须执行HTTP请求并自己返回WebResourceResponse.这是因为即使您像我一样修改标头,它们也会被忽略吗?

I've seen many answers on SO saying that you have to do the HTTP request and return WebResourceResponse yourself. Is this because even if you modify headers like I do, they are ignored?

我还试图在Android源代码中找到调用该文件的位置调用shouldInterceptRequest的位置在哪里,以便我自己查看其工作方式,但找不到.

I also trying to find the location in the Android source code of the call toWhere is the location of the call to the shouldInterceptRequest so I can see how it works myself, but I couldn't find it.

推荐答案

我自己找到了答案,就在文档:

I found the answer myself, it's right there in docs:

此外,一个简单的测试显示WebViewClient.shouldInterceptRequest返回null的基本实现.因此,WebView基本上继续像往常一样加载资源.

Moreover, a simple test shows the base implementation of WebViewClient.shouldInterceptRequest returns null. So the WebView basically continues to load resource as usual.

换句话说,我不能只向标头添加一个值并期望它被使用.我实际上需要亲自完成请求并返回响应.

In other words, I cannot just add a value to header and expect it to be used.I actually need to do the request myself and return the response.

太糟糕了,无法修改标头并让默认实现使用它.

Too bad there is no way to just modify header and have the default implementation use it.

我知道可以通过调用带有标题的loadUrl方法来设置标题,但是如果我先加载本地页面然后加载在线页面,则不会使用标题.

I know I can set in headers by calling loadUrl method with headers, but the headers won't be used if I'm first loading a local page and then load online pages.

这篇关于通过在ShouldInterceptRequest中向WebResourceRequest的标头添加标头来向WebView添加自定义标头不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 01:36