Java – how do I save a file from a Jersey response?
•
Java
I tried to download swf files from web resources using Jersey
I wrote the following code, but I couldn't 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();
Assume that the response does return the SWF file because the response Getmediatype returns application / x-shockwave-flash
However, when I tried to open SWF, nothing happened (and there were no errors), indicating that my file was not created from the response
Solution
I finally got its job
I came up with the idea of reading the Jersey API. I can directly use getentity to retrieve the InputStream of the response (assuming it has not been read)
Use getentity to retrieve InputStream and ioutils#tobytearray. It creates a byte array from InputStream. I try to make it 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
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码