从POST中获取415错误以下载文件

问题描述

我正在使用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"));

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...