gpt4 book ai didi

java - Jersey 客户端下载并保存文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:38:30 25 4
gpt4 key购买 nike

我是 jersey/JAX-RS 实现的新手。请在下面找到我的 Jersey 客户端代码以下载文件:

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

我的服务器端代码是:

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

在我的客户端代码中,我收到 200 OK 的响应,但我无法将我的文件保存在硬盘上在下面一行中,我提到了需要保存文件的路径和位置。不确定这里出了什么问题,我们将不胜感激。提前致谢!

File downloadfile = new File("C://Data/test/downloaded/testnew.pdf");

最佳答案

对于仍在寻找解决方案的人们,这里是关于如何将 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);
}

关于java - Jersey 客户端下载并保存文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24716357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com