Android的Webview在截取WebResourceResponse时怎样正常处理页面redirect重定向

在研究Android WebView的时候,有时需要截取页面响应,修改些信息再返回给WebView处理,期间发现如果页面返回302重定向到一个新的链接,而你正常返回302会有一个错误提示:

1
statusCode can't be in the [300, 399] range.

你说气人不气人…

所以只有曲线救国了,经过测试有2种方法可以实现:

方法1:直接让Webview加载新的链接:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String statusCode = 302; //get it from your response;
if (statusCode >= 300 && statusCode <= 399) {
final String newUrl = "https://example.com";
final myWebview = view;
view.post(new Runnable() {
@Override public void run() {
myWebview.loadUrl(newUrl);
}
});
WebResourceResponse nullRes = new WebResourceResponse("text/html", "utf-8", new ByteArrayInputStream("".getBytes()));
return nullRes;
}
}
方法2:修改WebResourceResponse,返回一个用js跳转新链接的html模板
1
2
3
4
5
6
7
8
9
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String statusCode = 302; //get it from your response;
if (statusCode >= 300 && statusCode <= 399) {
String newUrl = "https://example.com";
String content = "<script>location.href = '" + newUrl + "'</script>";
WebResourceResponse redirectRes = new WebResourceResponse("text/html", "utf-8", new ByteArrayInputStream(content.getBytes()));
return redirectRes;
}
}

这两个方法我也在Stackoverflow上做了解答:https://stackoverflow.com/questions/59965544/how-to-pass-webresourceresponse-with-redirect-code-to-android-webview-in-webvi/64605504#64605504