如何保存球衣响应中的文件? [英] How to save a file from jersey response?
问题描述
我正在尝试使用Jersey从Web资源下载SWF文件.
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();
可以节省下来,假定响应确实返回了SWF文件,因为response.getMediaType
返回了application/x-shockwave-flash
.
It is save to assume that the response does return a SWF file, as response.getMediaType
returns application/x-shockwave-flash
.
但是,当我尝试打开SWF时,什么也没有发生(也没有错误),这表明我的文件不是根据响应创建的.
However when I try to open the SWF, nothing happen (also no error) which suggest that my file was not created from response.
推荐答案
我终于可以使用它了.
我发现可以直接使用getEntity
检索response
的InputStream的Jersey API(假设尚未读取).
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).
使用getEntity
检索从InputStream
创建字节数组的InputStream
和IOUtils#toByteArray
,我设法使其起作用:
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();
请注意, IOUtils 是Apache的常用功能.
Note that IOUtils is a common Apache function.
这篇关于如何保存球衣响应中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!