0

I want to download a file and save it into my app folder. I have to download different files with different formats, but only one each time.

I've read that I have to use HttpUtils, but sample codes are to difficult for me (I'm too noob).

Can anyone upload any sample code?? Thanks!!

Manu
  • 1,130
  • 3
  • 10
  • 26

2 Answers2

1

This should point you in the right direction:

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();

Remember, you should never perform operations like this on the default UI tread. It could prompt the user to force close your app. Read more here: http://developer.android.com/resources/articles/painless-threading.html

Krylez
  • 17,414
  • 4
  • 32
  • 41
  • This is Java code. I'm developing with Basic4Android. Thanks anyway. – Manu Nov 02 '11 at 17:19
  • Then you should not include the Android-tag or at least cite in your question that it is related to Basic4Android. Krylez answer in this case was legitimate. – moster67 Nov 03 '11 at 12:45
  • If Basic4Android tag has been added, what do you think I'm asking for? – Manu Nov 04 '11 at 10:42
  • Manu-You added an Android-tag and as a response you got a legitimate answer in Java. Not what you wanted, right? Apparently B4A is not yet word-famous but since the Android-tag was there, Krylez was kind enough to give an answer. If we B4A-users only put the Basic4Android-tag, then we can avoid that all those helpful Java/Android SO-users loose their time. It's nothing personal and I wrote these comments on the B4A-forum as well. – moster67 Nov 04 '11 at 13:27
1

This is how I finally do:

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
Manu
  • 1,130
  • 3
  • 10
  • 26