0

Currently, I'm using this code in order to download a file:

ResponseEntity<Resource> response = this.restTemplate
    .getForEntity(
        uriToCall,
        Resource.class
    );

The problem is that code raises an OutOfMemoryError when I'm trying to download large files.

Is there any other way to get my large file avoiding this error?

EDIT: Another question.

I was thinking about applying FileSystemResource instead of Resource:

ResponseEntity<FileSystemResource> resp = this.restTemplate
    .getForEntity(
        uriToCall,
        FileSystemResource.class
    );

Which is the difference between FileSystemResource and Resource? That class is going to accomplish my goal?

Jordi
  • 20,868
  • 39
  • 149
  • 333

2 Answers2

1

For large files a better way is to use streams, so the size would only be limited by available disk space. Something like that should work:

this.restTemplate.execute(uriToCall, HttpMethod.GET, null, clientHttpResponse -> {
    File file= File.createTempFile("download", "tmp");
    StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(file));
});

See also this example for pause and resume.

stacker
  • 68,052
  • 28
  • 140
  • 210
  • I've edited post. Could you tell me something about `FileSystemResource`, instead of `Resource`? – Jordi Dec 19 '19 at 08:34
  • @Jordi You would use FileSystemResource when you want to upload a file to another service, in your case you really need to read a stream and write it to a file. – stacker Dec 19 '19 at 08:58
0

See the following for answer to similar issue:

How to forward large files with RestTemplate?

Create your RestTemplate as follows:

RestTemplate restTemplate = new RestTemplate();

SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setBufferRequestBody(false);
restTemplate.setRequestFactory(requestFactory);

This should resolve your out of memory issues.

Rob Scully
  • 744
  • 5
  • 10