2016-03-03 536 views
2

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

@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响应应该被捕获。

+2

web视图并不响应头提供接入。如果您需要访问这些数据,您必须使用HTTP客户端并自行检索页面。 http://stackoverflow.com/questions/3134389/access-the-http-response-headers-in-a-webview –

回答

1

尝试这个代码(需要API版本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/

+0

你知道如何从“WebResourceRequest请求”获取POST的请求正文吗? – Arya