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



我试图使用:ShouldInterceptRequest拦截webview请求,在其中我使用HttpUrlConnection从服务器获取数据,我将其设置为遵循重定向,这对webviewclient是透明的。这意味着当我返回WebResponseResource(",",data_inputstream)时,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".

有人能帮我吗?

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

在您的情况下,您正在HttpUrlConnection中使用重定向,因此WebView仍然认为它正在加载"http://www.google.com/"(即使内容来自"http://google.co.uk/")。如果谷歌主页没有明确设置基本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。然而,我强烈建议一般不要使用shouldInterceptRequest中的HttpUrlConnection——WebView的网络堆栈效率高得多,并且将并行执行获取(而使用shouldInterceptRequest将串行化KK之前WebView中的所有加载)。

关闭HttpClient setFollowRedirects(false)并使webview重新加载重定向的URL。

伪代码:

if(response.code == 302){
  webview.load(response.head("location"));
}

您可以为所有HttpURLConnection对象全局启用HTTP重定向:

HttpURLConnection.setFollowRedirects(true);

然后在shouldInterceptRequest()方法中检查连接响应代码:

public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
  ...
  int respCode = conn.getResponseCode();
  if( respCode >= 300 && respCode < 400 ) {
    // redirect
    return null;
  } else if( respCode >= 200 && respCode < 300 ) {
    // normal processing
    ...
}

安卓框架应该使用作为重定向目标的新URL再次调用shouldInterceptRequest(),这次连接响应代码将是2xx。

最新更新