如果我有一个 URL,当在 Web 浏览器中提交时,会弹出一个对话框来保存一个 zip 文件……我将如何在 android 中捕获和下载这个 zip 文件?
问问题
2122 次
2 回答
5
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();
}
}
于 2012-07-31T10:58:42.683 回答
0
使用DownloadManager下载 Url,虽然我不确定是否有任何重定向,但 DownloadManager 会处理它。
于 2012-07-31T10:58:27.930 回答