我想下载一个文件并将其保存到我的app文件夹中。我必须下载不同格式的不同文件,但每次只能下载一个。
我已经读过我必须使用HttpUtils,但样本代码对我来说很难(我太蠢了)。
任何人都可以上传任何示例代码吗?谢谢!
答案 0 :(得分:1)
这应该指向正确的方向:
URL u = new URL(urlString);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
File file = new File(outputDirectoryFile, outputFileName);
OutputStream out = new FileOutputStream(file);
InputStream in = c.getInputStream();
byte[] buffer = new byte[4096];
while ( (int len1 = in.read(buffer)) > 0 ) {
out.write(buffer,0, len1);
}
in.close();
out.close();
c.disconnect();
请记住,您绝不应在默认的UI页面上执行此类操作。它可能会提示用户强行关闭您的应用。在这里阅读更多: http://developer.android.com/resources/articles/painless-threading.html
答案 1 :(得分:1)
这就是我最终的做法:
imgurl = "http://dl.dropbox.com/u/25045/file.jpg"
HttpUtils.CallbackActivity = "myactivity" 'Current activity name.
HttpUtils.CallbackJobDoneSub = "JobDone"
HttpUtils.Download("Job1", imgurl)
Dim out As OutputStream
out = File.OpenOutput(File.DirInternal, "file.jpg", True)
File.Copy2(HttpUtils.GetInputStream(imgurl), out)
out.Close