How to save file from jersey response?

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

I wrote the following code, but I cannot save the file correctly:

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(); 

Save to suggest that the response returns a SWF file, since response.getMediaType returns application/x-shockwave-flash .

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

+6
source share
3 answers

I finally got it for work.

I realized that I had read the Jersey API, which I could use getEntity directly to retrieve an InputStream from response (if it has not already been read).

Using getEntity to retrieve an InputStream and IOUtils#toByteArray that create an array of bytes from an InputStream , I managed to get it working:

 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 generic Apache feature.

+6
source

Starting with Java 7, you can also use the new NIO API to write the input stream to a file:

 InputStream is = response.readEntity(InputStream.class) Files.copy(is, new File(...).toPath()); 
+6
source

I think you should not go through String.

If the answer is really a SWF file (binary data), then here:

 String binarySWF = response.readEntity(String.class); 

instead of this code (which reads a string), just try reading an array of bytes. See if this helps. Strings refer to encodings
and maybe it will ruin everything.

+1
source

Source: https://habr.com/ru/post/959192/


All Articles