7

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!

jvnbt
  • 2,465
  • 4
  • 20
  • 23

3 Answers3

19

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

Rigo Sarmiento
  • 434
  • 5
  • 21
Blackbelt
  • 156,034
  • 29
  • 297
  • 305
  • Perfect. The fact that response.getEntity().getContent() gives an input stream was the missing piece of the puzzle. Thanks. – jvnbt Nov 01 '13 at 19:15
0

First is the method:

public HttpResponse setHTTPConnection() throws IOException, NullPointerException, URISyntaxException {
       HttpClient client = HttpClientBuilder.create().build();
       HttpRequestBase requestMethod = new HttpGet();
       requestMethod.setURI(new URI("***FileToDownlod***"));
       BasicHttpContext localContext = new BasicHttpContext();


       return client.execute(requestMethod, localContext);
   }

Second is an actual code:

File downloadedFile = new File("filePathToSave");
       HttpResponse fileToDownload = setHTTPConnection();
       try {
           FileUtils.copyInputStreamToFile(fileToDownload.getEntity().getContent(), downloadedFile);
       } finally {
           fileToDownload.getEntity().getContent().close();
       }

Please make sure to change "filePathToSave" to where to save the file and "FileToDownlod" to from where to download accordingly.

"filePathToSave" is where you want to save the file, if you choose to save it locally then you can simply point to the desktop but don't forget to give a name to your file like "/Users/admin/Desktop/downloaded.pdf" (in Mac).

"FileToDownlod" is in the form of URL e.g "https://www.doesntexist.com/sample.pdf"

Don't panic as the second piece will ask to declare in throws clause or catch multiple exceptions. This piece of code was for a specific purpose please customize for your own need.

Raccoon
  • 21
  • 2
0

As you said response is content of book or simple meaning that you are getting response as file but not able to save response as file.

Use this

HttpResponse<Path> response = client.send(request, HttpResponse.BodyHandlers.ofFile(Paths.get("/sdcard/test.epub"));