使用 Java 中的“Content-Disposition"标题通过 REST 服务下载 PDF 文件 [英] Download a PDF file via REST service with “Content-Disposition” Header in java
问题描述
我正在尝试在自定义身份验证检查后从 Java REST 调用的响应中下载 PDF 文件.
我可以看到下载的文件,但它是空文件.
下面是我的代码片段.
//自定义HTTPClientHTTPAuthClient 客户端 = 新的 HTTPAuthClient(url,username,password)请求请求 = 新请求(下载地址);//我正在下载一个 URL 的文件内容.响应 response = client.executeGet(request);String response1 = response.getResponseBody();InputStream is = new ByteArrayInputStream(response.getBytes());response.setContentType("Content-type",application/pdf);//这里的响应是//javax.servlet.HttpServletResponseresponse.setHeader("Content-Disposition","attachment;filename="myfile.pdf");IOUtils.copy(is,response.getOutPutStream());response.flushBuffer();
使用此代码我可以下载文件,但是当我打开文件并验证没有数据时.作为响应正文的一部分,我还可以看到一些数据.
你能帮我找出我做错的地方吗?我尝试了很多选择,但没有找到解决方案.
如何使用 setContentType
response.setContentType("Content-type",application/pdf);
如果这个方法中只有一个可用的参数是 String void setContentType(String type)
那么你的方法应该是:
response.setContentType("application/pdf");
Java 文档是肯定的.>
I am trying to download a PDF file from a response of Java REST call after custom authentication check.
I can see downloaded file but it is empty file.
Below is my code snippet.
//Custom HTTPClient
HTTPAuthClient client = new HTTPAuthClient(url,username,password)
Request request = new Request(downloadURL); //I'm downloading file content of an URL.
Response response = client.executeGet(request);
String response1 = response.getResponseBody();
InputStream is = new ByteArrayInputStream(response.getBytes());
response.setContentType("Content-type",application/pdf); //here response is //javax.servlet.HttpServletResponse
response.setHeader("Content-Disposition","attachment;filename="myfile.pdf");
IOUtils.copy(is,response.getOutPutStream());
response.flushBuffer();
With this code I could download the file but when I open the file and verified there is no data. As part of response body also I can see some data.
Could you please help me out where I'm doing mistake I tried many options but did not find solution.
How can you use setContentType like this
response.setContentType("Content-type",application/pdf);
If only one avalible param in this method is String void setContentType(String type)
so your method should be:
response.setContentType("application/pdf");
Java Doc to be sure.
这篇关于使用 Java 中的“Content-Disposition"标题通过 REST 服务下载 PDF 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!