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
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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 =
                                                         .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


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java EE

From novice to tech pro — start learning today.