What to do with IOException in WebViewClient.shouldInterceptRequest ()

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) {
            // what should we do now?
            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);
}
+4
2

WebResourceError, WebViewClient.onReceivedError. , :

} catch (final IOException e) {
    WebResourceError wre = new WebResourceError(){
        @Override
        public CharSequence getDescription (){
            return e.toString(); 
        }

        @Override
        public int getErrorCode (){
            return WebViewClient.ERROR_CONNECT;
        }
    };

    onReceivedError(view, request, wre);

    return true;
}

onReceivedError, , WebResourceError.

+1

, - -. , -.

IOException() IOException .

IOException ( String) IOException .

IOException ( String, Throwable cause) IOException .

IOException (Throwable cause) IOException ( == null? Null: cause.toString()) ( pically ).

IOException

:

http://examples.javacodegeeks.com/core-java/io/ioexception/java-io-ioexception-how-to-solve-ioexception/

-1

Source: https://habr.com/ru/post/1625484/


All Articles