I am trying to intercept requests from a WebView so that I can add extra headers. I am applying WebViewClient to WebView and overriding shouldInterceptRequest().
Q. shouldInterceptRequest()I open a connection, add headers and return an open stream to WebResourceResponse.
I don't understand how to handle an IOException if the initial opening of the connection fails.
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) {
e.printStackTrace();
}
return super.shouldInterceptRequest(view, request);
}
});
I cannot leave it undetected, as this is a checked exception and is not part of the signature shouldInterceptRequest().
I cannot wrap it in an unchecked exception, since then it does not appear in the WebView and kills the application.
, super ( null), WebView ( ). , WebView , .
, , , .
?
, . 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);
}