Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a file from jersey response?

Tags:

java

rest

jersey

I am trying to download a SWF file using Jersey from a web resource.

I have written the following code, but am unable to save the file properly :

Response response = webResource.request(MediaType.APPLICATION_OCTET_STREAM)
  .cookie(cookie)
  .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));

String binarySWF = response.readEntity(String.class);                                     
byte[] SWFByteArray = binarySWF.getBytes();       

FileOutputStream fos = new FileOutputStream(new File("myfile.swf"));
fos.write(SWFByteArray);
fos.flush();
fos.close();

It is save to assume that the response does return a SWF file, as response.getMediaType returns application/x-shockwave-flash.

However when I try to open the SWF, nothing happen (also no error) which suggest that my file was not created from response.

like image 493
Jean-François Savard Avatar asked Dec 02 '13 19:12

Jean-François Savard


People also ask

How do I download a file from Jersey?

2. Jersey file download demo. If you hit the URL, “ http://localhost:8080/JerseyDemos/rest/download/pdf “, you will get below shown alert in your browser to download the file. The filename with which PDF file will be saved, will be what you set in Response.


2 Answers

From Java 7 on, you can also make use of the new NIO API to write the input stream to a file:

InputStream is = response.readEntity(InputStream.class)
Files.copy(is, Paths.get(...));
like image 139
ocroquette Avatar answered Oct 19 '22 14:10

ocroquette


I've finally got it to work.

I figured out reading the Jersey API that I could directly use getEntity to retrieve the InputStream of the response (assuming it has not been read yet).

Using getEntity to retrieve the InputStream and IOUtils#toByteArray which create a byte array from an InputStream, I managed to get it to work :

Response response = webResource.request(MediaType.APPLICATION_OCTET_STREAM)
  .cookie(cookie)
  .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));                                                  

InputStream input = (InputStream)response.getEntity();

byte[] SWFByteArray = IOUtils.toByteArray(input);  

FileOutputStream fos = new FileOutputStream(new File("myfile.swf"));
fos.write(SWFByteArray);
fos.flush();
fos.close();

Note that IOUtils is a common Apache function.

like image 44
Jean-François Savard Avatar answered Oct 19 '22 16:10

Jean-François Savard