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

adm*_*vin 5 redirect android webview android-webview webviewclient

我正在尝试使用以下方法拦截 webview 请求:ShouldInterceptRequest在其中我用来HttpUrlConnection从服务器获取数据,我将其设置为遵循重定向,这对 webviewclient 是透明的。这意味着当我返回 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);

            }
        }
Run Code Online (Sandbox Code Playgroud)

如果我请求“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文件”。

任何人都可以帮助我吗?

mar*_*iba 1

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

在您的情况下,您正在使用 中的重定向HttpUrlConnection,因此 WebView 仍然认为它正在加载“ http://www.google.com/ ”(即使内容来自“ http://google.co.英国/ ”)。如果 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在这种情况下返回。不过,我强烈建议不要一般使用HttpUrlConnectionfrom shouldInterceptRequest- WebView 的网络堆栈效率更高,并且会并行执行获取(而 usingshouldInterceptRequest将序列化 KK 之前的 WebView 中的所有加载)。