从WebView下载文件返回HTML内容,而不是实际文件 [英] Downloading file from webview returns HTML content not the actual file
本文介绍了从WebView下载文件返回HTML内容,而不是实际文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用downloadListener从Webview下载文件.可以正确识别文件名,但是会下载html内容.如果相关,我正在尝试下载.apk文件.
I am using a downloadListener to download a file from a webview. The filename is correctly recognized, however the html content is downloaded. In case it is relevant, I am trying to download an .apk file.
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 以及用户代理添加到request属性.
Update: The solution is to add the cookie as well as the user-agent to the request property.
String cookie = CookieManager.getInstance().getCookie(url);
con.setRequestProperty("cookie",cookie);
con.setRequestProperty("User-Agent",userAgent);
这篇关于从WebView下载文件返回HTML内容,而不是实际文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文