Man*_*anu 7 java rest spring jackson maven
关于这类问题,我读了很多关于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);
Run Code Online (Sandbox Code Playgroud)
使用时Accept:*/*在映射请求时产生错误(404发生)
从我的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>
Run Code Online (Sandbox Code Playgroud)
我也尝试添加这两个依赖项,但没有任何变化:
<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>
Run Code Online (Sandbox Code Playgroud)
响应客户端:There was an unexpected error (type=Not Acceptable, status=406).标题包括:
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Run Code Online (Sandbox Code Playgroud)
它出什么问题了?
我使用此代码返回远程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;
Run Code Online (Sandbox Code Playgroud)
基本上没有必要添加produces = "application/pdf"RequestMapping,因为它似乎试图在内部转换ResponeBody.您只需添加MediaType到您需要的响应标头即可.
@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"));
return new ResponseEntity<InputStreamResource> (inputStreamResource,
responseHeaders,
HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9500 次 |
| 最近记录: |