HTTP 406下载具有休息呼叫的文件

时间:2016-04-13 19:50:11

标签: java spring rest

我遵循这个tutorial来实现带有Spring Boot的rest API以下载文件(xml格式)。

我的控制器类如下:

@RestController
public class RistoreController {
    @Autowired
    private RistoreService ristoreService;

    @RequestMapping( 
            value = "/ristore/foundation/{trf}", 
            method = RequestMethod.GET, 
            produces = "application/xml")
    public ResponseEntity<InputStream> getXMLById(@PathVariable("trf") String trf) throws IOException {
        InputStream inputStream = ristoreService.findByTRF(trf);
        return ResponseEntity
                .ok()
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(inputStream);
    }
}

我在控制器中自动连接服务接口RistoreService,该服务的Bean类如下所示:

@Service
public class RistoreServiceBean implements RistoreService {
    public InputStream findByTRF(String trf) throws IOException {
        String filePath = "/Users/djiao/Box Sync/Work/Projects/RIStore/foundation/foundation_new/" + trf + ".xml";
        File file = new File(filePath);
        return new FileInputStream(file);
    }
}

我使用以下curl命令测试了应用程序:

curl -i -H "Accept: application/xml" http://localhost:8080/ristore/foundation/TRF133672_1455294493597

然而,我得到406错误,&#34;不可接受&#34;。文件格式有问题吗?

2 个答案:

答案 0 :(得分:1)

代码中的以下两行相互矛盾:

            .contentType(MediaType.parseMediaType("application/octet-stream"))

        produces = "application/xml")

答案 1 :(得分:1)

尝试以那种方式更改控制器的定义

        @RequestMapping(value = "/ristore/foundation/{trf}", method = RequestMethod.GET, produces = "application/xml")
    public ResponseEntity<InputStreamResource> downloadXMLFile(@PathVariable("trf") String trf)
            throws IOException {

        // Optinal headers configuration 

HttpHeaders headers = new HttpHeaders();

        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");


        // get the inputStream

    InputStream xmlFileInputStream = ristoreService.findByTRF(trf);



        return ResponseEntity
                .ok()
                .headers(headers)
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(xmlFileInputStream));
    }

然后你的服务类将是:

 @Service
public class RistoreServiceBean implements RistoreService {
    public InputStream findByTRF(String trf) throws IOException {
        String filePath = "/Users/djiao/Box Sync/Work/Projects/RIStore/foundation/foundation_new/" + trf + ".xml";
        File file = new File(filePath);
        return new FileInputStream(file);
    }
}
  

406不可接受   请求标识的资源只能根据请求中发送的接受标头生成具有不可接受的内容特征的响应实体。

这意味着只要有REST控制器,就必须将返回的输入流视为资源。