androidhttpresponsehttpentity

Saving BufferedHttpEntity to File


How do you save an entity to SDCard, in a streamed manner (To avoid memory issues).

I cant find any solid documentation on the matter.

        response = httpClient.execute(request);

        BufferedHttpEntity responseEntity = new BufferedHttpEntity(response.getEntity());

        FileOutputStream fos = new FileOutputStream(Files.SDCARD + savePath);

        responseEntity.writeTo(fos);

        fos.flush();
        fos.close();

This gives me the file, but with no contents. (2KB in size). So its not writing properly.

The server is sending a FileStream. Which I have confirmed to work.


Solution

  • I would try this approach:

    HttpResponse response = httpClient.execute(post);    
    
    InputStream input = response.getEntity().getContent();
    OutputStream output = new FileOutputStream("path/to/file");
    int read = 0;
    
    byte[] bytes = new byte[1024];
    while ((read = input.read(bytes)) != -1) {
        output.write(bytes, 0, read);
    }
    output.close();
    

    Hope it helps. Cheers.