如何解决从WebView下载文件返回HTML内容而不是实际文件
我正在使用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,len);
total += len;
}
output.close();
is.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
});
解决方法
更新:解决方案是将 cookie 以及用户代理添加到request属性。
String cookie = CookieManager.getInstance().getCookie(url);
con.setRequestProperty("cookie",cookie);
con.setRequestProperty("User-Agent",userAgent);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。