【发布时间】:2016-01-22 10:56:56
【问题描述】:
我正在尝试拦截来自 WebView 的请求,以便注入额外的标头。我正在将 WebViewClient 应用到 WebView 并覆盖 shouldInterceptRequest()。
在shouldInterceptRequest() 中,我打开连接,添加标头,然后在 WebResourceResponse 中返回打开的流。
如果连接的初始打开失败,我不清楚应该如何处理 IOException。
final Map<String, String> extraHeaders = getExtraHeaders(intent);
webview.setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
final Uri uri = request.getUrl();
try {
URL url = new URL(uri.toString());
URLConnection con = url.openConnection();
for (Map.Entry<String, String> h : extraHeaders.entrySet()) {
con.addRequestProperty(h.getKey(), h.getValue());
}
final String contentType = con.getContentType().split(";")[0];
final String encoding = con.getContentEncoding();
return new WebResourceResponse(contentType, encoding, con.getInputStream());
} catch (IOException e) {
// what should we do now?
e.printStackTrace();
}
return super.shouldInterceptRequest(view, request);
}
});
我不能让它不被发现,因为它是一个已检查的异常并且不是shouldInterceptRequest() 签名的一部分。
我不能将它包装在未经检查的异常中,因为它不会被 WebView 捕获并杀死应用程序。
如果我捕获并忽略异常,并默认使用 super 方法(它只返回 null),那么 WebView 将继续其默认行为并尝试发送请求(没有我的额外标头)。这是不可取的,因为 WebView 自己的连接尝试实际上可能会成功,而缺少的 headers 会导致更多的问题。
似乎没有办法表明拦截失败,应该中止请求。
这里最好做什么?
我已尝试返回模拟失败响应,但这不会被视为错误。 WebView 显示一个包含响应内容(来自异常的错误消息)的页面,并且未调用 WebViewClient 的 onReceivedError() 或 onReceivedHttpError() 回调。
} catch (IOException e) {
InputStream is = new ByteArrayInputStream(e.getMessage().getBytes());
return new WebResourceResponse("text/plain", "UTF-8", 500, "Intercept failed",
Collections.<String, String>emptyMap(),
is);
}
【问题讨论】:
标签: android android-webview httprequest ioexception