英文:
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();
}
});
英文:
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();
}
});
答案1
得分: 0
更新:解决方案是将cookie和用户代理(user-agent)一并添加到请求属性中。
String cookie = CookieManager.getInstance().getCookie(url);
con.setRequestProperty("cookie", cookie);
con.setRequestProperty("User-Agent", userAgent);
英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论