【发布时间】:2020-09-15 19:22:56
【问题描述】:
我正在使用 downloadListener 从 webview 下载文件。文件名被正确识别,但是 html 内容被下载。如果它是相关的,我正在尝试下载一个 .apk 文件。
webView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
new Thread(new Runnable() {
@Override
public void run() {
InputStream is;
try {
final String filename= URLUtil.guessFileName(url, contentDisposition, mimetype);
Log.d("download","filename: "+filename);//filename is correct
URL u = new URL(url);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("GET");
con.connect();
is = con.getInputStream();
// Path and File where to download the APK
File apk = new File(getFilesDir(),filename);
FileOutputStream output = new FileOutputStream(apk);
// Save file from URL
byte[] buffer = new byte[1024];
int len = 0;
long total=0;
while ((len = is.read(buffer)) != -1) {
output.write(buffer, 0, len);
total += len;
}
output.close();
is.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
});
【问题讨论】:
-
这个问题可能很愚蠢,但
url是否指向正确的网址,您是否可以从该网址下载文件,例如curl或wget? -
to download a file from a webview.?从你的意思的服务器。或网站。 -
发布 html 内容。查看html。它告诉你什么?您将使用重定向网址。
-
在浏览器上下载工作绝对正常,文件也被正确识别,否则它不会返回它的名字。
-
@blackapps 在常规浏览器中,将下载文件并重定向 url。但是我不确定这是否会造成任何麻烦。
标签: java android webview download