【发布时间】:2020-12-17 19:47:52
【问题描述】:
我正在使用 Spring Rest 下载一个 zip 文件,其内容由文档 ID 列表确定。
我的控制器是这样的
@RestController
@RequestMapping("api/zip-documents")
public class DocumentsRestController {
@Autowired
private DocumentDownloadService documentDownloadService;
@PostMapping(produces = {"application/zip"}, consumes = {"application/json"})
public ResponseEntity<Resource> downloadZip(@RequestBody List<String> documentIds) throws IOException {
// Zip the documents into a file
ByteArrayOutputStream outputStream = documentDownloadService.downloadZip(documentIds);
ByteArrayResource resource = new ByteArrayResource(outputStream.toByteArray());
return ResponseEntity.ok().header("Content-Disposition", "attachment; filename=\"file.zip\"")
.contentLength(outputStream.size()).body(resource);
}
}
我使用 Mockito 的测试如下,运行应用时也遇到同样的问题:
@Test
public void downloadZip_sunnyDayUseCase_contentTypeIsZip() throws Exception {
Mockito.when(documentDownloadService.downloadZip(Matchers.anyListOf(String.class)))
.thenReturn(new ByteArrayOutputStream());
mockMvc
.perform(post("/api/zip-documents")
.content("{ \"documentIds\": [\"123123\"] }"))
.andExpect(status().isOk())
.andExpect(content().contentType("application/zip"));
}
我收到 HttpStatus 415 响应。这似乎是请求标头的问题,因为我无法在 restcontroler 中打断点。
【问题讨论】:
标签: java spring rest http-headers file-type