首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Android WebView有时不会在初始页面加载时发送请求头

Android WebView有时不会在初始页面加载时发送请求头
EN

Stack Overflow用户
提问于 2019-02-25 14:59:59
回答 1查看 1.2K关注 0票数 6

我有一个webview活动,它在onCreate()方法中加载一个带有几个自定义请求头的URL。要求传递带有初始URL请求的自定义标头。在一些设备上,webview在webview活动启动几次之后停止发送标头。

例如,我有一个启动HomeActivity的WebViewActivity。在启动WebViewActivity并导航回HomeActivity几次之后,WebViewActivity停止发送自定义请求头,除非我清除应用程序的数据,否则这种行为不会改变。

我已经用MITM工具证实了这种行为。执行情况如下:

代码语言:javascript
运行
复制
@Override
protected void onCreate(Bundle savedInstanceState) {

    Map<String, String> map = new HashMap<>();
    map.put("header1", "header1_value");
    map.put("header2", "header2_value");
    map.put("header3", "header3_value");
    map.put("header4", "header4_value");
    webView.loadUrl("https://www.example.com/mypath", map);

}

上面的片段在每次活动启动时都无条件地执行。但是,在webview提出的实际请求中不存在标头。另外,请求的页面是303重定向。

EN

回答 1

Stack Overflow用户

发布于 2019-03-08 14:48:01

如果您的最小API目标是21级,则可以使用shouldInterceptRequest level您可以使用

每次拦截时,您将需要获取url,自己发出请求,并返回内容流:

然后:

代码语言:javascript
运行
复制
WebViewClient wvc = new WebViewClient() {
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {

        try {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("header1", "header1_value");
            httpGet.setHeader("header2", "header2_value");
            httpGet.setHeader("header3", "header3_value");
            httpGet.setHeader("header4", "header4_value");
            HttpResponse httpReponse = client.execute(httpGet);

            Header contentType = httpReponse.getEntity().getContentType();
            Header encoding = httpReponse.getEntity().getContentEncoding();
            InputStream responseInputStream = httpReponse.getEntity().getContent();

            String contentTypeValue = null;
            String encodingValue = null;
            if (contentType != null) {
                contentTypeValue = contentType.getValue();
            }
            if (encoding != null) {
                encodingValue = encoding.getValue();
            }
            return new WebResourceResponse(contentTypeValue, encodingValue, responseInputStream);
        } 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;
        }
    }
}

//Where wv is your webview
wv.setWebViewClient(wvc);

基于这个问题

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54868993

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档