【问题标题】:Getting 415 error from POST to download file从 POST 获取 415 错误以下载文件
【发布时间】: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


    【解决方案1】:

    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"));
    

    【讨论】:

    • 这是部分正确的。而且,我的 json 是错误的。它应该看起来像 "[\"123123\", \"321654\"]"
    猜你喜欢
    • 2019-01-26
    • 2012-01-06
    • 2021-10-16
    • 2017-09-07
    • 1970-01-01
    • 2019-05-03
    • 2011-02-21
    • 2020-07-21
    • 1970-01-01
    相关资源
    最近更新 更多