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..?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With