gpt4 book ai didi

Android WebViewClient url重定向(Android URL加载系统)

转载 作者:太空狗 更新时间:2023-10-29 15:27:03 35 4
gpt4 key购买 nike

我尝试使用以下方法拦截 webview 请求:ShouldInterceptRequest,在其中我使用 HttpUrlConnection 从服务器获取数据,我将其设置为遵循重定向,这对网页浏览客户端。这意味着当我返回 WebResponseResource("", "", data_inputstream) 时,webview 可能不知道目标主机已更改。我怎样才能告诉 webview 这件事发生了?

ourBrowser.setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view,
String url) {
..... //some code omitted here

HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) newUrl.openConnection();
conn.setFollowRedirects(true);
} catch (IOException e) {
e.printStackTrace();
}
..... //

InputStream is = null;
try {
is = conn.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return new WebResourceResponse(mimeType, encoding, is);

}
}

如果我请求“google.com”,它应该被重定向到“google.co.uk”,但是 webview 不知道重定向,如果“co.uk”附加的 css 文件的链接是“/render/something.css”,webview 仍然去“http://www.google.com/render/something.css”找到应该是“http://www.google.co.uk/render/something.css”的 css 文件。

谁能帮帮我?

最佳答案

某些元数据(url、 header 等)不能由 WebResourceResponse 指定类(class)。这意味着您只能使用 shouldInterceptRequest提供不同的数据(更改页面的内容),但您不能使用它来更改加载它的 URL。

在您的情况下,您正在 HttpUrlConnection 中使用重定向,所以 WebView 仍然认为它正在加载“http://www.google.com/”(即使内容来自“http://google.co.uk/”)。如果 Google 的主页没有明确设置基本 URL,WebView 将继续假定基本 URL 为“http://www.google.com/”(因为它没有看到重定向)。由于相对资源引用(如 <link href="//render/something.css" />)是根据 baseURL(在本例中是“http://www.google.com/”而不是“http://www.google.co.uk/”)解析的,因此您会得到观察到的结果。

你可以做的是使用 HttpUrlConnection确定您要加载的 URL 是否是重定向并返回 null在这种情况下。但是我强烈建议不要使用 HttpUrlConnection来自 shouldInterceptRequest一般来说 - WebView 的网络堆栈效率更高,并且将并行执行提取(而使用 shouldInterceptRequest 将序列化 KK 之前的 WebView 中的所有负载)。

关于Android WebViewClient url重定向(Android URL加载系统),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18237451/

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