Android:WebView shouldInterceptRequest不在WebView中添加RequestProperties

时间:2017-01-26 08:10:37

标签: android webview android-webview

我使用shouldInterceptRequest

拦截来自webview的请求

下面是我的返回我的WebResourceResponse

的代码
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private static WebResourceResponse handleRequestViaUrlOnly(WebResourceRequest webResourceRequest){
        String url = webResourceRequest.getUrl().toString();
        Log.i("intercepting req....!!!", url);
        String ext = MimeTypeMap.getFileExtensionFromUrl(url);
        String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);

        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestProperty("Sample-Header", "hello");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            return new WebResourceResponse(mime, "UTF-8", conn.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

我在CustomWebViewClient

中调用此方法
class CustomWebViewClient extends WebViewClient {

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        return handleRequestViaUrlOnly(request);
    }
}

但是,当我在chrome:// inspect /#devices中检查来自WebView远程调试器的请求标头时。

我添加的其他RequestProperty不存在。

conn.setRequestProperty("Sample-Header", "hello");

WebView中的请求标头中没有Sample-Header。

我错过了什么吗?我会感激任何帮助。

1 个答案:

答案 0 :(得分:1)

所以问题是,当你传递conn.getInputStream()时,它只提供数据。可以通过conn.getHeaderFields()提取响应标头。此外,除非服务器支持并且不涉及CORS,否则您将无法获得额外的标头。这是连接的wireshark输出

GET /~fdc/sample.html HTTP/1.1
Sample-Header: hello
Content-Type: application/x-www-form-urlencoded
User-Agent: Dalvik/2.1.0 (Linux; U; Android 7.1; Android SDK built for x86_64 Build/NPF26K)
Host: www.columbia.edu
Connection: Keep-Alive
Accept-Encoding: gzip
Content-Length: 0

HTTP/1.1 200 OK
Date: Wed, 01 Mar 2017 09:06:58 GMT
Server: Apache
Last-Modified: Thu, 22 Apr 2004 15:52:25 GMT
Accept-Ranges: bytes
Vary: Accept-Encoding,User-Agent
Content-Encoding: gzip
Content-Length: 8664
Keep-Alive: timeout=15, max=99
Connection: Keep-Alive
Content-Type: text/html

正如您所看到的,响应中没有Sample-Header: hello标头。

以下是从响应中构建WebResourceResponse标头并将自定义标头附加到其中的简单代码:

webView.setWebViewClient(new WebViewClient() {
    private Map<String, String> convertResponseHeaders(Map<String, List<String>> headers) {
        Map<String, String> responseHeaders = new HashMap<>();
        responseHeaders.put("Sample-Header", "hello");

        for (Map.Entry<String, List<String>> item : headers.entrySet()) {
            List<String> values = new ArrayList<String>();

            for (String headerVal : item.getValue()) {
                values.add(headerVal);
            }
            String value = StringUtil.join(values, ",");
            Log.e(TAG, "processRequest: " + item.getKey() + " : " + value);

            responseHeaders.put(item.getKey(), value);
        }

        return responseHeaders;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        final String method = request.getMethod();
        final String url = request.getUrl().toString();
        Log.d(TAG, "processRequest: " + url + " method " + method);
        String ext = MimeTypeMap.getFileExtensionFromUrl(url);
        String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);

        try {
            HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
            conn.setRequestMethod(method);
            conn.setRequestProperty("Sample-Header", "hello");
            conn.setDoInput(true);
            conn.setUseCaches(false);

            Map<String, String> responseHeaders = convertResponseHeaders(conn.getHeaderFields());

            responseHeaders.put("Sample-Header", "hello");

            return new WebResourceResponse(
                    mime,
                    conn.getContentEncoding(),
                    conn.getResponseCode(),
                    conn.getResponseMessage(),
                    responseHeaders,
                    conn.getInputStream()
                    );

        } catch (Exception e) {
            Log.e(TAG, "shouldInterceptRequest: " + e);
        }
        return null;
    }
});