0

Getting the above error when trying to download large data using HttpGet

String uri = "";
getMethod = executeGet(uri);
httpClient.executeMethod(getMethod);
InputStream istream  = getMethod.getResponseBodyAsStream();
byte[] data = IOUtils.toByteArray(istream);
FileUtils.writeByteArraytoFile(new  File("xxx.zip"),data)
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
user3798050
  • 39
  • 1
  • 1
  • 3

2 Answers2

1

You are using a temporary byte array that might be the cause of the problem. You can directly write the content of the stream to your file.

String uri = "";
getMethod = executeGet(uri);
httpClient.executeMethod(getMethod);
InputStream istream  = getMethod.getResponseBodyAsStream();
IOUtils.copy(istream, new FileOutputStream(new  File("xxx.zip"));
YMomb
  • 2,366
  • 1
  • 27
  • 36
1

You're reading the entire response into the byte[] (memory). Instead, you could stream the output as you read it from istream with something like,

File f = new  File("xxx.zip");
try (OutputStream os = new BufferedOutputStream(new FileOutputStream(f));) {
    int c = -1;
    while ((c = istream.read()) != -1) {
        os.write(c);
    }
} catch (Exception e) {
    e.printStackTrace();
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249