Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebView does not render HTML/gzip content, which is received via HttpURLConnection in shouldInterceptRequest() webViewClient method

Android 21+

We have a WebViewClient which overrides shouldInterceptRequest method. In this method, we make an HTTP GET request manually and pass received InputStream as a WebResourceResponse, fully expecting WebView to display received data. Received content is gzipped HTML.

@Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            HttpURLConnection urlc = null;
            try {
                URL url = new URL(request.getUrl().toString());
                urlc = (HttpURLConnection) network.openConnection(url); // network instance is received via some other way, unrelated to this problem
                urlc.setRequestMethod("HEAD");
                urlc.connect();

                String contentType = urlc.getContentType();
                String contentEncoding = urlc.getContentEncoding();
                urlc.disconnect();

                urlc = (HttpURLConnection) network.openConnection(url);
                urlc.connect();

                return new WebResourceResponse(contentType, contentEncoding, urlc.getInputStream());
            } catch (Exception e) {
               ...
            }

However, WebView displays only text - it doesn't display proper HTML, it only displays raw content, this is an example of what is shown on the page:

<html>
<head>SomeTitle</head>
<body>content....</body>
</html>

Looks like it either doesn't understand that provided data is HTML, or fails to parse it (maybe because of gzip?). Or is something else going on?

Content-type and content-encoding received with HEAD call are:

HEAD REQUEST | CONTENT TYPE: text/html;charset=UTF-8 | ENCODING: gzip

and are passed to WebResourceResponse, as shown in the code above.

Any ideas..?

like image 833
Ivan Avatar asked Feb 24 '26 20:02

Ivan


1 Answers

It seems to be necessary to remove the semi-colon and everything after it from the content type string.

int semicolon = contentType.indexOf(';');
if (semicolon >= 0) {
    contentType = contentType.substring(0, semicolon).trim();
}
like image 161
Jim Hawkins Avatar answered Feb 27 '26 10:02

Jim Hawkins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!