[英]Android WebView: Download when content-type is application/pdf and render web page if not
我有一个特定的场景,我在正文中使用唯一的票证发出POST
请求以返回结果页面。
结果页面是Content-Type
: application/pdf
或text/html
。 门票仅有效一次,因此页面只能加载一次。
问题是 Android WebView不支持 pdf 的渲染(与 iOS 上的等价物一样)。
我尝试了以下方法:
检查带有主要请求的 http 响应标头,然后使用第二个请求下载文件(如果它是 pdf)并在 PDF 应用程序中打开它(有效)。 但是对于加载 html 页面,第二个请求失败,因为票不再有效。
下载 pdf 和 html 页面,然后在本地打开 pdf 应用程序/WebView。 这是有效的,网页中的两个相对链接都已损坏。 有没有好的方法可以下载它们?
X。 是否可以中断 WebView 中的请求以读取响应标头并触发下载(如果它是 pdf),否则继续渲染? 找不到一个好的答案。
您可以将内置方法URLConnection.getContentType()用于确切目的。 获得内容类型后,继续下载或传递给WebView
。
进口:
import java.net.URL;
import java.net.URLConnection;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
这是在加载之前拦截 URL 的示例:
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String requestedUrl = request.getUrl().toString();
boolean isDownloadableFile = false;
try {
isDownloadableFile = new FetchContentTypeAsync(requestedUrl).execute().get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
// downloadable file / dont load it in webview
if (isDownloadableFile) {
// download the file here
return false;
} else {
// non downloadable file / load it in webview
view.loadUrl(requestedUrl);
return super.shouldOverrideUrlLoading(view, request);
}
}
});
FetchContentTypeAsync用于后台运行任务
private static class FetchContentTypeAsync extends AsyncTask<Void, Void, Boolean> {
private String requestedUrl;
FetchContentTypeAsync(String requestedUrl) {
this.requestedUrl = requestedUrl;
}
@Override
protected Boolean doInBackground(Void... voids) {
boolean isDownloadableFile = false;
try {
URL url = new URL(requestedUrl);
URLConnection urlConnection = url.openConnection();
String contentType = urlConnection.getContentType();
isDownloadableFile = contentType.equalsIgnoreCase("application/pdf");
} catch (IOException e) {
e.printStackTrace();
}
return isDownloadableFile;
}
}
设置 WebViewClient 后,它有一些接口来拦截请求,最广泛使用的是shouldOverrideUrlLoading()
但你也可以覆盖shouldInterceptRequest()
并在那里拦截它。
webView.setWebViewClient(new WebViewClient() {
@Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Check the URL here - if it is a file,
// then initiate the download
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.