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

时间:2019-02-25 14:59:59

标签: android http webview header

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

例如,我有一个HomeActivity,它可以启动WebViewActivity。启动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);

}

以上代码段在每次启动活动时无条件执行。但是,标头不存在于Webview发出的实际请求中。另外,请求的页面是303重定向。

1 个答案:

答案 0 :(得分:0)

如果您的最低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