How to load HttpResponse into a file?

My Android application uses an API that sends a multi-page HTTP request. I successfully get the answer like this:

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

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

A file can be up to 20 MB, so it will need to use some kind of stream, but I just can't wrap it around. Thanks!

+6
source share
1 answer

Well, this is a simple task, you need to use the WRITE_EXTERNAL_STORAGE permission .. then just get an InputStream

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

Create FileOutputStream

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

and read from is and write using fos

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

Change, check for tyoo

+12
source

Source: https://habr.com/ru/post/957213/


All Articles