RestTemplate: Download a Zip file

Dear sirs,
I would like to have a sample code demonstrating how to download a ZIP file using Spring RestTemplate.
I can do it using Jersey, I have hard time doing with Spring RestTemplate.
Please, assist
Omer-PitouAsked:
Who is Participating?
 
girionisConnect With a Mentor Commented:
There are two ways you can do it. a) use a ResponseExtractor, and b) read the whole response as byte [].

If you want to use a byte [] :

ResponseEntity<byte[]> response = restTemplate.build()
                                                         .exchange("<URL TO ZIP FILE>", HttpMethod.GET, entity, byte[].class);
           Files.write(Paths.get("path to your local disk to save the zip"), response.getBody());

Open in new window


If you want to use a ResponseExtractor:

RequestCallback req= request -> request.getHeaders()
        .setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));

ResponseExtractor<Void> re = response -> {
    Path path = Paths.get("path to file that you want to save");
    Files.copy(response.getBody(), path);
    return null;
};
restTemplate.execute(URI.create("URL of the zip file"), HttpMethod.GET, req, re);

Open in new window

0
 
Omer-PitouAuthor Commented:
Thanks a lot. This is what I was missing
headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL)
I used headers.setContentType(MediaType.APPLICATION_OCTET_STREAM), instead, and wonder why it didn't  work.
Again thanks a lot.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.