gpt4 book ai didi

java - WebView 不渲染 HTML/gzip 内容,该内容是通过 shouldInterceptRequest() webViewClient 方法中的 HttpURLConnection 接收的

转载 作者:行者123 更新时间:2023-11-30 02:34:52 25 4
gpt4 key购买 nike

Android 21+

我们有一个 WebViewClient 重写 shouldInterceptRequest 方法。在此方法中,我们手动发出 HTTP GET 请求,并将接收到的 InputStream 作为 WebResourceResponse 传递,完全期望 WebView 显示接收到的数据。收到的内容是 gzip 压缩的 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) {
...
}

但是,WebView 仅显示文本 - 它不显示正确的 HTML,它仅显示原始内容,这是页面上显示的内容的示例:

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

看起来它要么不理解提供的数据是 HTML,要么无法解析它(可能是因为 gzip?)。还是发生了其他事情?

通过 HEAD 调用收到的内容类型和内容编码为:

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

并传递给 WebResourceResponse,如上面的代码所示。

有什么想法吗..?

最佳答案

似乎有必要从内容类型字符串中删除分号及其后面的所有内容。

int semicolon = contentType.indexOf(';');
if (semicolon >= 0) {
contentType = contentType.substring(0, semicolon).trim();
}

关于java - WebView 不渲染 HTML/gzip 内容,该内容是通过 shouldInterceptRequest() webViewClient 方法中的 HttpURLConnection 接收的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43342728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com