问题描述
我在我的应用中使用 WebView
,我必须拦截请求。我目前正在使用以下代码来执行此操作。
I am using a WebView
in my app in which I must intercept requests. I am currently using the follwing code to do it.
public WebResourceResponse shouldInterceptRequest (WebView view, String url) {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestProperty("User-Agent", userAgent);
String mime;
if (url.lastIndexOf('.') > url.lastIndexOf('/')) {
String ext = url.substring(url.lastIndexOf('.') + 1);
mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
} else {
mime = "text/html";
}
return new WebResourceResponse(mime, "UTF-8", conn.getInputStream());
}
以上代码在大多数情况下都能正常工作,但并非全部。例如,当我尝试登录Outlook时,它只是显示我的电子邮件或密码不正确,我还看到其他请求被破坏的情况,但如果我删除 shouldInterceptRequest 。
Above code works fine in most cases, but no all. For example when I try to login to Outlook, it just shows that my email or password is incorrect, I have also seen other cases in which requests get broken, but everything works fine if I remove
shouldInterceptRequest
.
我目前用来拦截请求的方法有哪些更好的方式?
Is there any better way that the one I am currently using to intercept requests?
推荐答案
您的代码存在两个问题
- 扩展检测不正确
例如,当代码尝试获取此URL的资源扩展时:
For example, when the code try to get resource extension for this URL:
https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=12&ct=1442476202&rver=6.4.6456.0&wp=MBI_SSL_SHARED&wreply=https:%2F%2Fmail.live.com%2Fdefault.aspx%3Frru%3Dinbox&lc=1033&id=64855&mkt=en-us&cbcxt=mai
它将返回
aspx%3Frru%3Dinbox& lc = 1033& id = 64855& mkt = en-us& cbcxt = mai
这是错的。有一种从URL获取扩展的特殊方法:
It will return
aspx%3Frru%3Dinbox&lc=1033&id=64855&mkt=en-us&cbcxt=mai
which is wrong. There is special method for getting extension from the URL: getFileExtensionFromUrl()
- 根据文档方法可能会返回
null
。在这种情况下,您的代码为页面设置了错误的mime类型。
According to documentation method
MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext)
may returnnull
. In this case your code set wrong mime type for the page.
以下是考虑这两个问题的方法代码
Here is the method code that take into account both these issues
@Override
public WebResourceResponse shouldInterceptRequest(WebView view,
String url) {
String ext = MimeTypeMap.getFileExtensionFromUrl(url);
String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
if (mime == null) {
return super.shouldInterceptRequest(view, url);
} else {
HttpURLConnection conn = (HttpURLConnection) new URL(
url).openConnection();
conn.setRequestProperty("User-Agent", userAgent);
return new WebResourceResponse(mime, "UTF-8",
conn.getInputStream());
}
}
这篇关于在Android中拦截WebView请求的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!