【问题标题】:Get response headers in webview in shouldInterceptRequest in Android在 Android 的 shouldInterceptRequest 中获取 webview 中的响应标头
【发布时间】:2016-03-03 09:51:10
【问题描述】:

当我向服务器发布一些 url 时,我试图在 webview 中获取响应标头。我正在使用 shouldInterceptRequest 方法。

@Override 
        public WebResourceResponse shouldInterceptRequest(final WebView view, final WebResourceRequest request) {

            if(request.getUrl().toString().contains(SMConstant.INTERCEPTED_URL)){
                if(interceptFlag==0){
                    ((Activity) mContext).runOnUiThread(new Runnable(){
                        @Override
                        public void run() {
                            view.postUrl(request.getUrl().toString(), EncodingUtils.getBytes(postData, "UTF-8"));
                        }
                    });
                    interceptFlag++;
                }

            }
            return super.shouldInterceptRequest(view, request);
        }

此方法返回 WebResourceResponse 对象。但我不知道如何从中获取响应标头。

默认情况下return super.shouldInterceptRequest(view, request); 返回 null。

那么,应该怎么做才能捕获实际的 webview 响应。

【问题讨论】:

标签: android webview response


【解决方案1】:

试试这个代码(需要 API VERSION 21):

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            if (request.getUrl().toString().contains("some_char")) {// condition to intercept webview's request
                return handleIntercept(request);
            } else
                return super.shouldInterceptRequest(view, request);
        }
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private WebResourceResponse handleIntercept(WebResourceRequest request){
    OkHttpClient okHttpClient = new OkHttpClient();
    final Call call = okHttpClient.newCall(new Request.Builder()
            .url(request.getUrl().toString())
            .method(request.getMethod(),null)
            .headers(Headers.of(request.getRequestHeaders()))
            .build()
    );
    try {
        final Response response = call.execute();
        response.headers();// get response header here
        return new WebResourceResponse(
                response.header("content-type", "text/plain"), // You can set something other as default content-type
                response.header("content-encoding", "utf-8"),  //you can set another encoding as default
                response.body().byteStream()
        );
    } catch (IOException e) {
        e.printStackTrace();
        return null
    }
}

参考: Access the http response headers in a WebView?

https://artemzin.com/blog/use-okhttp-to-load-resources-for-webview/

【讨论】:

  • 您知道如何从“WebResourceRequest 请求”中获取 POST 的请求正文吗?
猜你喜欢
  • 1970-01-01
  • 2019-04-04
  • 1970-01-01
  • 1970-01-01
  • 2021-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多