从 webview 下载文件 returns HTML 内容不是实际文件
Downloading file from webview returns HTML content not the actual file
我正在使用 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();
}
});
更新:解决方案是将 cookie 以及 user-agent 添加到请求 属性.
String cookie = CookieManager.getInstance().getCookie(url);
con.setRequestProperty("cookie",cookie);
con.setRequestProperty("User-Agent",userAgent);
我正在使用 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();
}
});
更新:解决方案是将 cookie 以及 user-agent 添加到请求 属性.
String cookie = CookieManager.getInstance().getCookie(url);
con.setRequestProperty("cookie",cookie);
con.setRequestProperty("User-Agent",userAgent);