Gra*_*and 5 android httprequest ioexception android-webview
我试图拦截来自 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);
}
});
Run Code Online (Sandbox Code Playgroud)
我不能让它不被发现,因为它是一个已检查的异常并且不是shouldInterceptRequest()签名的一部分。
我不能将它包装在一个未经检查的异常中,因为它会被 WebView 捕获并杀死应用程序。
如果我捕获并忽略异常,并默认使用该super方法(仅返回null),则 WebView 将继续其默认行为并尝试发送请求(没有我额外的标头)。这是不可取的,因为 WebView 自己的连接尝试实际上可能会成功,而缺少的标头会导致更多的问题。
似乎没有办法表明拦截失败,应该中止请求。
在这里做什么最好?
我试图返回模拟失败响应,但这不被视为错误。WebView 显示包含响应内容(来自异常的错误消息)的页面,并且不会调用WebViewClientonReceivedError()或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);
}
Run Code Online (Sandbox Code Playgroud)
小智 -1
表示发生了某种 I/O 异常。此类是由失败或中断的 I/O 操作产生的一般异常类。
IOException() 构造一个 IOException,并将 null 作为其错误详细信息。
IOException(String message) 使用指定的详细消息构造 IOException。
IOException(String message, Throwable Cause) 使用指定的详细消息和原因构造 IOException。
IOException(Throwable Cause) 使用指定的原因和 (cause==null ? null : Cause.toString()) 的详细消息构造 IOException(通常包含 Cause 的类和详细消息)。
你有关于 IOException 的例子
这里 :
| 归档时间: |
|
| 查看次数: |
784 次 |
| 最近记录: |