terça-feira, 14 de dezembro de 2010

Rest with Jersey: Creating a Restful zip download funcionality.

It's very simple create RESTFul Web Services with Jersey. I'll demonstrate how to create a simple one that provide a dowload of a compressed file. 

First, let's see how to compress a file in Java. If you wanna learn more about, then click here. I use ZipOutputStream because I wanna send the zip file through OutputStream provided by Servlet Response object, but you can send an existent zip file if you prefer. So let's go to the code:


This method is quite simple, It just writes the File parameter inside the ZipOutputStream, that encapsulates our OutputStream, I didn't close the Stream because I wanna compress several files.
Right now let's see how to create our Rest class:























The main points are the annotation @Produces and the header Content-Disposition. The first one is used to specify the MIME media types of representations a resource can produce and send back to the client, in our example we will send a zip file back to the client. The header Content-Disposition allow us to set the file name for the client, if you don't wanna use it the file name will be the same of the rest method name.

After add all desired files we need flush and close the stream and return an 'ok' response, if something goes wrong we send an INTERNAL_SERVER_ERROR status response. When the user requests the resource (like this: http://localhost:8084/jersey-sample/resources/downloader/downloadall/ he will receive a zip file to download and the suggested name will be the same configured in the header Content-Disposition.

It's just for now. Until the next post.

2 comentários:

  1. Hi , Im using zip4j. When i try to download, it throws an error:
    A message body writer for Java class net.lingala.zip4j.core.ZipFile, and Java type class net.lingala.zip4j.core.ZipFile, and MIME media type application/octet-stream was not found

    How do i fix this

    ResponderExcluir
  2. I tried application/zip as well, but it threw the same error

    ResponderExcluir