如果我有一个URL,当在网络浏览器中提交时,会弹出一个对话框来保存一个zip文件...我该如何在android中捕获并下载这个zip文件?
答案 0 :(得分:4)
public void downloadFromUrl(String url, String outputFileName) {
File dir = new File(Environment.getExternalStorageDirectory() + "/");
if (dir.exists() == false) {
dir.mkdirs();
}
try {
URL downloadUrl = new URL(url); // you can write any link here
File file = new File(dir, outputFileName);
/* Open a connection to that URL. */
URLConnection ucon = downloadUrl.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
答案 1 :(得分:0)
使用DownloadManager下载Url,虽然我不确定是否有重定向,但DownloadManager会处理它。