users@jersey.java.net

Re: Downloading file using Jersey client API ?

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Fri, 29 Feb 2008 09:43:19 +0100

James Weir wrote:
> My question is how do I use the Client API to retrieve the contents and
> store them locally on disk ?
> At the moment I am battling to get it to work. Any ideas ? or examples
> you have so I can see how to do this ?

You can do this:

   ResourceProxy r = ... // note that i am going to rename this to
                         // WebResource
   File f = r.get(File.class);

but it will create the file in a temporary directory location (i am not
sure if you can specify what that temporary location should be using a
system property). Then you could move the file from the temporary
location using renameTo.


Alternatively you can do this:

   ResourceProxy r = ... // note that i am going to rename this to
                         // WebResource
   InputStream in = r.get(InputStream.class);
   FileOutputStream out = new FileOutputStream(<location>);
   // Read bytes from in and write bytes to out.

It sucks a bit because it would be nice to pass in an instance of File,
but that is not the way the message body readers work. I think you could
encapsulate the above functionality in a helper, as follows:

   FileCreator.create(<location>, r.get(InputStream.class));


> Also, am I setting the MediaType correctly here ?, I am currently using
> MimeTypeMap to get the mime type of the file

What API is "MimeTypeMap" from ? I presume it tries to guess the media
type from the file name and the contents (magic number).

You can set the entity and the media type using ok:

   return Response.ok(in, mt).
          lastModified(lastModified).tag(et).build();

Paul.

-- 
| ? + ? = To question
----------------\
    Paul Sandoz
         x38109
+33-4-76188109