我在 SO 上阅读了很多关于此类问题的问题,但他们都建议使用正确的 Jackson 版本。这是我的现状:
REST API:
@RequestMapping(value = "get/pdf/{id}", headers="Accept=*/*", method = RequestMethod.GET, produces = "application/pdf")
@Override
public ResponseEntity<InputStream> getPdfContractById(@PathVariable("id") Long id);
使用 Accept:*/*
会在映射请求时产生错误(发生 404)
来 self 的 pom:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1.1</version>
</dependency>
我也尝试添加这两个依赖,但没有任何变化:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
响应客户端:出现意外错误(type=Not Acceptable,status=406)。
header 包括:
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
这是怎么回事?
更多详情
我正在使用此代码返回远程 PDF 文件:
URL url = null;
try {
url = new URL(urlStr);
} catch (MalformedURLException e) {
e.printStackTrace();
throw new MyException(e.getMessage());
}
InputStream pdfFile = null;
try {
pdfFile = url.openStream();
} catch (IOException e) {
e.printStackTrace();
throw new MyException(e.getMessage());
}
ResponseEntity<InputStream> re = ResponseEntity
.ok()
// .headers(headers)
// .contentLength(contentLength)
.contentType(
MediaType.parseMediaType("application/pdf"))
.body(pdfFile);
return re;
最佳答案
基本上没有必要在 RequestMapping 中添加 produces = "application/pdf"
因为它似乎试图在内部转换 ResponeBody。您只需将 MediaType
添加到您需要的响应 header 即可。
@ResponseBody
@RequestMapping(value = "get/pdf/{id}", headers="Accept=*/*", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> getPdfContractById(@PathVariable("id") Long id){
// Get the remove file based on the fileaddress
RemoteFile remotefile = new RemoteFile(id);
// Set the input stream
InputStream inputstream = remotefile.getInputStream();
// asume that it was a PDF file
HttpHeaders responseHeaders = new HttpHeaders();
InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
responseHeaders.setContentLength(contentLengthOfStream);
responseHeaders.setContentType(MediaType.valueOf("application/pdf"));
// just in case you need to support browsers
responseHeaders.put("Content-Disposition", Collections.singletonList("attachment; filename=somefile.pdf"))
return new ResponseEntity<InputStreamResource> (inputStreamResource,
responseHeaders,
HttpStatus.OK);
}
关于java - Spring REST 返回 PDF - 响应状态 406( Not Acceptable ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33876635/