简体   繁体   中英

Getting 415 error from POST to download file

I am using Spring Rest to download a zip file, then contents of which are determined by a list of document ids.

My Controller is like so

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

My test, using Mockito is as follows, and I also get the same issue when running the app:

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

I'm getting a HttpStatus 415 response. This seems to be an issue with the request header, as I cannot hit a breakpoint in the restcontroler.

HTTP Status Code 415 stands for Unsupported Media Type . Since you are trying to post JSON data to the endpoint, you probably want a Content-Type: application/json header somewhere in your POST.

So, in your mockMvc , I guess try the following:

mockMvc
            .perform(post("/api/zip-documents")
                    .header("Content-Type", "application/json")
                    .content("{ \"documentIds\": [\"123123\"] }"))
            .andExpect(status().isOk())
            .andExpect(content().contentType("application/zip"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM