目标:
覆盖WebView发出的所有请求,并自己发出请求(最终设置代理).
码:
@Override public WebResourceResponse shouldInterceptRequest(WebView view,String url) { if (url == null || url.trim().equals("")) return null; final DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getConnectionManager().closeExpiredConnections(); final HttpUriRequest httpRequest = new HttpGet(url); try { final HttpResponse response = httpClient.execute(httpRequest); final Header[] headers = response.getHeaders(CONTENT_TYPE); String mimeType = ""; String encoding = ""; if (headers != null && headers.length > 0) { final String type = headers[0].getValue(); final int semicolonIndex = type.indexOf(';'); if (semicolonIndex != -1) { mimeType = type.substring(0,semicolonIndex).trim(); encoding = type.substring(semicolonIndex + 1).trim(); final int equalsIndex = encoding.indexOf('='); if (equalsIndex != -1) encoding = encoding.substring(equalsIndex + 1).trim(); } else mimeType = type; } return new WebResourceResponse(mimeType,encoding,response.getEntity().getContent()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } finally { httpClient.getConnectionManager().closeExpiredConnections(); } return null; }
所有这些请求似乎都很好,但是最终我得到了以下两个问题之一的堆栈跟踪:
3 15:07:28.650 E/InputDispatcher( 3981): channel '40d76268 com.secure.browser/com.secure.browser.SecureBrowserActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x8 01-03 15:07:28.650 E/InputDispatcher( 3981): channel '40d76268 com.secure.browser/com.secure.browser.SecureBrowserActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
这显然是指示文件描述符(fid)中的操作系统耗尽的
要么
01-03 15:29:36.810 I/DEBUG ( 5798): 5903cd34 ac81c0b7 /system/lib/libdvm.so 01-03 15:29:38.380 I/DEBUG ( 5798): debuggerd committing suicide to free the zombie! 01-03 15:29:38.380 I/BootReceiver( 3981): Copying /data/tombstones/tombstone_07 to DropBox
(SYSTEM_TOMBSTONE)
这意味着我认为这意味着操作系统正在处于低级问题.
当我打开javascript,或者浏览一段时间后没有javascript,这大部分失败.
解决方法
我只是有一个评论,我看到一开始你返回null如果URL是空的,或者如果是空或只是空格,但在
documentation你可以看到“返回 包含响应信息的WebResourceResponse或如果WebView应该加载资源本身,则为null“,所以如果这是你想要的,如果不是我会推荐super.shouldInterceptRequest(视图,”“),因为空URL可能导致一些麻烦.