gpt4 book ai didi

java - HTTP 406 通过休息调用下载文件

转载 作者:行者123 更新时间:2023-11-30 02:58:25 25 4
gpt4 key购买 nike

我关注了这个tutorial使用Spring Boot实现rest API来下载文件(xml格式)。

我的 Controller 类如下:

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

我在 Controller 中 Autowiring 了服务接口(interface) 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 错误“ Not Acceptable ”。文件格式有问题吗?

最佳答案

尝试以这种方式更改 Controller 的定义

        @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 Not Acceptable The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.

这意味着一旦您拥有 REST Controller ,您返回的输入流就必须被视为资源。

关于java - HTTP 406 通过休息调用下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36608231/

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