Java Jersey 客户端下载和保存文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24716357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jersey client to download and save file
提问by cxyz
I Am new to jersey/JAX-RS implementation. Please find below my jersey client code to download file:
我是 jersey/JAX-RS 实现的新手。请在我的球衣客户端代码下方找到下载文件:
Client client = Client.create();
WebResource wr = client.resource("http://localhost:7070/upload-0.0.1-SNAPSHOT/rest/files/download");
Builder wb=wr.accept("application/json,application/pdf,text/plain,image/jpeg,application/xml,application/vnd.ms-excel");
ClientResponse clientResponse= wr.get(ClientResponse.class);
System.out.println(clientResponse.getStatus());
File res= clientResponse.getEntity(File.class);
File downloadfile = new File("C://Data/test/downloaded/testnew.pdf");
res.renameTo(downloadfile);
FileWriter fr = new FileWriter(res);
fr.flush();
My Server side code is :
我的服务器端代码是:
@Path("/download")
@GET
@Produces({"application/pdf","text/plain","image/jpeg","application/xml","application/vnd.ms-excel"})
public Response getFile()
{
File download = new File("C://Data/Test/downloaded/empty.pdf");
ResponseBuilder response = Response.ok((Object)download);
response.header("Content-Disposition", "attachment; filename=empty.pdf");
return response.build();
}
In my client code i am getting response as 200 OK,but i am unable to save my file on hard disk In the below line i am mentioning the path and location where the files need to be saved. Not sure whats going wrong here,any help would be appreciated.Thanks in advance!!
在我的客户端代码中,我得到的响应为 200 OK,但我无法将文件保存在硬盘上 在下面的行中,我提到了需要保存文件的路径和位置。不知道这里出了什么问题,任何帮助将不胜感激。提前致谢!!
File downloadfile = new File("C://Data/test/downloaded/testnew.pdf");
采纳答案by Paul Jowett
I don't know if Jersey let's you simply respond with a file like you have here:
我不知道 Jersey 是否让你简单地回复一个文件,就像你在这里的一样:
File download = new File("C://Data/Test/downloaded/empty.pdf");
ResponseBuilder response = Response.ok((Object)download);
You cancertainly use a StreamingOutput response to send the file from the server, like this:
你可以肯定使用StreamingOutput响应从服务器发送的文件,就像这样:
StreamingOutput stream = new StreamingOutput() {
@Override
public void write(OutputStream os) throws IOException,
WebApplicationException {
Writer writer = new BufferedWriter(new OutputStreamWriter(os));
//@TODO read the file here and write to the writer
writer.flush();
}
};
return Response.ok(stream).build();
and your client would expect to read a stream and put it in a file:
并且您的客户希望读取流并将其放入文件中:
InputStream in = response.getEntityInputStream();
if (in != null) {
File f = new File("C://Data/test/downloaded/testnew.pdf");
//@TODO copy the in stream to the file f
System.out.println("Result size:" + f.length() + " written to " + f.getPath());
}
回答by pNut
For folks still looking for a solution, here is the complete code on how to save jaxrs response to a File.
对于仍在寻找解决方案的人们,这里是有关如何将 jaxrs 响应保存到文件的完整代码。
public void downloadClient(){
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:7070/upload-0.0.1-SNAPSHOT/rest/files/download");
Response resp = target
.request("application/pdf,image/jpeg,application/xml,application/vnd.ms-excel")
.get();
if(resp.getStatus() == Response.Status.OK.getStatusCode())
{
InputStream is = resp.readEntity(InputStream.class);
fetchFeed(is);
//fetchFeedAnotherWay(is) //use for Java 7
IOUtils.closeQuietly(is);
System.out.println("the file details after call:"+downloadfile.getAbsolutePath()+", size is "+downloadfile.length());
}
else{
throw new WebApplicationException("Http Call failed. response code is"+resp.getStatus()+". Error reported is"+resp.getStatusInfo());
}
}
/**
* Store contents of file from response to local disk using java 7
* java.nio.file.Files
*/
private void fetchFeed(InputStream is){
File downloadfile = new File("C://Data/test/downloaded/testnew.pdf");
byte[] byteArray = IOUtils.toByteArray(is);
FileOutputStream fos = new FileOutputStream(downloadfile);
fos.write(byteArray);
fos.flush();
fos.close();
}
/**
* Alternate way to Store contents of file from response to local disk using
* java 7, java.nio.file.Files
*/
private void fetchFeedAnotherWay(InputStream is){
File downloadfile = new File("C://Data/test/downloaded/testnew.pdf");
Files.copy(is, downloadfile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
回答by RuntimeException
This sample code below may help you.
下面的示例代码可能对您有所帮助。
https://stackoverflow.com/a/32253028/15789
https://stackoverflow.com/a/32253028/15789
This is a JAX RS rest service, and test client. It reads bytes from a file and uploads the bytes to the REST service. The REST service zips the bytes and sends it back as bytes to the client. The client reads the bytes and saves the zipped file. I had posted this as a response to another thread.
这是一个 JAX RS 休息服务和测试客户端。它从文件中读取字节并将字节上传到 REST 服务。REST 服务压缩字节并将其作为字节发送回客户端。客户端读取字节并保存压缩文件。我发布了这个作为对另一个线程的回应。
回答by Michael Pawlowsky
Here's another way of doing it using Files.copy().
这是使用 Files.copy() 的另一种方法。
private long downloadReport(String url){
long bytesCopied = 0;
Path out = Paths.get(this.fileInfo.getLocalPath());
try {
WebTarget webTarget = restClient.getClient().target(url);
Invocation.Builder invocationBuilder = webTarget.request(MediaType.TEXT_PLAIN_TYPE);
Response response = invocationBuilder.get();
if (response.getStatus() != 200) {
System.out.println("HTTP status " response.getStatus());
return bytesCopied;
}
InputStream in = response.readEntity( InputStream.class );
bytesCopied = Files.copy(in, out, REPLACE_EXISTING);
in.close();
} catch( IOException e ){
System.out.println(e.getMessage());
}
return bytesCopied;
}