【问题标题】:Android WebView sometimes doesn't send request headers on initial page loadAndroid WebView 有时不会在初始页面加载时发送请求标头
【发布时间】:2019-02-25 14:59:59
【问题描述】:

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

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

我已使用 MITM 工具确认了此行为。实现如下:

@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);

}

上述 sn-p 在每次活动启动时无条件执行。但是,标头不存在于 webview 发出的实际请求中。此外,被请求的页面是 303 重定向。

【问题讨论】:

  • 我想你可以在这篇文章中找到你的答案:stackoverflow.com/questions/7610790/…
  • @MahdiKhardani 这是一个不同的问题。在这里,webview 本身并没有发送任何带有初始页面请求的自定义标头。
  • 离开屏幕后不能清除缓存吗

标签: android http webview header


【解决方案1】:

如果您的最低 API 目标是 21 级,您可以使用 shouldInterceptRequest 否则您可以使用 this

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

然后:

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);

基于此question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 2015-09-23
    • 1970-01-01
    • 2014-02-24
    相关资源
    最近更新 更多