Env*_*nve 16 java android webview
我WebView在我的应用程序中使用a ,我必须拦截请求.我目前正在使用以下代码来执行此操作.
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());
}
Run Code Online (Sandbox Code Playgroud)
上面的代码在大多数情况下工作正常,但并非全部.例如,当我尝试登录到Outlook时,它只显示我的电子邮件或密码不正确,我还看到了其他请求被破坏的情况,但如果我删除,一切正常shouldInterceptRequest.
有没有更好的方法,我目前用来拦截请求?
Ily*_*kov 12
您的代码有两个问题
例如,当代码尝试获取此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
Run Code Online (Sandbox Code Playgroud)
它将返回aspx%3Frru%3Dinbox&lc=1033&id=64855&mkt=en-us&cbcxt=mai哪个是错误的.有一种从URL获取扩展的特殊方法:getFileExtensionFromUrl()
MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext)可能会返回null.在这种情况下,您的代码为页面设置了错误的mime类型.以下是考虑这两个问题的方法代码
@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());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6203 次 |
| 最近记录: |