访问WebView中的http响应头?

tro*_*man 39 android

有一种方法可以在WebView中加载网页后查看活动中的http响应标头吗?似乎这应该是可能的,但我找不到任何暴露标题的方法.

Cri*_*ian 32

既不提供WebView也不WebViewClient提供方法,但是,您可以尝试手动实现.你可以这样做:

private WebView webview;
public void onCreate(Bundle icicle){
    // bla bla bla

    // here you initialize your webview
    webview = new WebView(this);
    webview.setWebViewClient(new YourWebClient());
}

// this will be the webclient that will manage the webview
private class YourWebClient extends WebViewClient{

    // you want to catch when an URL is going to be loaded
    public boolean  shouldOverrideUrlLoading  (WebView  view, String  urlConection){
        // here you will use the url to access the headers.
        // in this case, the Content-Length one
        URL url;
        URLConnection conexion;
        try {
            url = new URL(urlConection);
            conexion = url.openConnection();
            conexion.setConnectTimeout(3000);
            conexion.connect();
            // get the size of the file which is in the header of the request
            int size = conexion.getContentLength();
        }


        // and here, if you want, you can load the page normally
        String htmlContent = "";
        HttpGet httpGet = new HttpGet(urlConection);
        // this receives the response
        HttpResponse response;
        try {
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                // la conexion fue establecida, obtener el contenido
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    InputStream inputStream = entity.getContent();
                    htmlContent = convertToString(inputStream);
                }
            }
         } catch (Exception e) {}

         webview.loadData(htmlContent, "text/html", "utf-8");
         return true;
    }

    public String convertToString(InputStream inputStream){
        StringBuffer string = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                string.append(linea + "\n");
            }
        } catch (IOException e) {}
        return string.toString();
    }
}
Run Code Online (Sandbox Code Playgroud)

我现在无法测试它,但这基本上就是你可以做的(尽管它非常疯狂:).

  • 自问这个问题以来已有4年了.我想知道是否有任何完全准备好的解决方案?或者这仍然是最好的方式?如果是这样,httpClient来自哪里? (5认同)
  • 用这种方法唯一的问题是在调用的WebView使用loadURL时shouldOverrideUrlLoading()不叫().这对我来说是个大问题. (2认同)
  • 我认为这不会很好用,因为似乎只有forOverrideUrlLoading为GET请求调用.如果您想拦截POST请求中的标头怎么办?shouldInterceptRequest是更合适的方法,但它需要棒棒糖. (2认同)

小智 5

受到Cristian 回答的启发,我需要拦截 webview 正在执行的 AJAX 调用,我需要拦截响应标头以获取一些信息(电子商务应用程序中的购物车项目计数),我需要在应用程序中利用这些信息。由于应用程序正在使用 okhttp,我最终做到了这一点并且它正在工作

        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            Log.i(TAG,"shouldInterceptRequest path:"+request.getUrl().getPath());
            WebResourceResponse returnResponse = null;
            if (request.getUrl().getPath().startsWith("/cart")) { // only interested in /cart requests
                returnResponse = super.shouldInterceptRequest(view, request);
                Log.i(TAG,"cart AJAX call - doing okRequest");
                Request okRequest = new Request.Builder()
                        .url(request.getUrl().toString())
                        .post(null)
                        .build();
                try {
                    Response okResponse = app.getOkHttpClient().newCall(okRequest).execute();
                    if (okResponse!=null) {
                        int statusCode = okResponse.code();
                        String encoding = "UTF-8";
                        String mimeType = "application/json";
                        String reasonPhrase = "OK";
                        Map<String,String> responseHeaders = new HashMap<String,String>();
                        if (okResponse.headers()!=null) {
                            if (okResponse.headers().size()>0) {
                                for (int i = 0; i < okResponse.headers().size(); i++) {
                                    String key = okResponse.headers().name(i);
                                    String value = okResponse.headers().value(i);
                                    responseHeaders.put(key, value);
                                    if (key.toLowerCase().contains("x-cart-itemcount")) {
                                        Log.i(TAG,"setting cart item count");
                                        app.setCartItemsCount(Integer.parseInt(value));
                                    }
                                }
                            }
                        }
                        InputStream data = new ByteArrayInputStream(okResponse.body().string().getBytes(StandardCharsets.UTF_8));
                        Log.i(TAG, "okResponse code:" + okResponse.code());
                        returnResponse = new WebResourceResponse(mimeType,encoding,statusCode,reasonPhrase,responseHeaders,data);
                    } else {
                        Log.w(TAG,"okResponse fail");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return returnResponse;
        }
Run Code Online (Sandbox Code Playgroud)

我希望这可能对其他人有所帮助,如果有人有改进建议,我将不胜感激。不幸的是,它仅与 LOLLIPOP 和更高版本兼容,因为从这个版本开始,您可以使用WebResourceRequest访问/返回标头,这是我的案例所需要的。