Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download an HttpResponse into a file?

My android app uses an API which sends a multipart HTTP request. I am successfully getting the response like so:

post.setEntity(multipartEntity.build());
HttpResponse response = client.execute(post);

The response is the contents of an ebook file (usually an epub or mobi). I want to write this to a file with a specified path, lets says "/sdcard/test.epub".

File could be up to 20MB, so it'll need to use some sort of stream, but I can just can't wrap my head around it. Thanks!

like image 585
user1023127 Avatar asked Nov 01 '13 19:11

user1023127


1 Answers

well it is a simple task, you need the WRITE_EXTERNAL_STORAGE use permission.. then simply retrieve the InputStream

InputStream is = response.getEntity().getContent();

Create a FileOutputStream

FileOutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "test.epub"));

and read from is and write with fos

int read = 0;
byte[] buffer = new byte[32768];
while( (read = is.read(buffer)) > 0) {
  fos.write(buffer, 0, read);
}

fos.close();
is.close();

Edit, check for tyoo

like image 50
Blackbelt Avatar answered Nov 10 '22 15:11

Blackbelt