问题描述
我正在使用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中碰到断点。
解决方法
HTTP状态代码415
代表Unsupported Media Type
。由于您尝试将JSON数据发布到端点,因此您可能希望在POST中的某个位置放置一个Content-Type: application/json
头。
因此,我想在您的mockMvc
中尝试以下操作:
mockMvc
.perform(post("/api/zip-documents")
.header("Content-Type","application/json")
.content("{ \"documentIds\": [\"123123\"] }"))
.andExpect(status().isOk())
.andExpect(content().contentType("application/zip"));