Android 我可以使用Webview从网站下载pdf吗?
我使用webview创建了我的第一个应用程序,在应用程序中显示一个网站,但通过单击一个链接浏览该网站,我无法在智能手机上从该网站下载任何文件。我怎样才能用一种简单的方式做到这一点 多谢各位Android 我可以使用Webview从网站下载pdf吗?,android,webview,Android,Webview,我使用webview创建了我的第一个应用程序,在应用程序中显示一个网站,但通过单击一个链接浏览该网站,我无法在智能手机上从该网站下载任何文件。我怎样才能用一种简单的方式做到这一点 多谢各位 首先,您需要在webview中截取url webview.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view
首先,您需要在webview中截取url
webview.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// clicked url, a.k.a pdf download link
// here you can check if this link is what you want, e.x. if(url.contains("pdf"))
// then you pass this link to your downloader
downloadPdf();
return true;
}
});
下面是从url下载文件的方法。使用Asyntask在后台执行方法
传递文件url和文件完整路径(目录+名称)
谢谢,但是有没有一种方法可以从web域启用所有下载?
public static void downloadPdf(String fileUrl, File fileFullPath){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}