You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot RestController接收application/octet-stream报415错误的解决办法

解决Spring Boot POST端点接收二进制流的415异常问题

问题根源是Spring默认的消息转换器无法将application/octet-stream类型的请求体转换为RequestEntity<InputStream>,导致触发HttpMediaTypeNotSupportedException。可以通过以下几种方式修改Controller实现来解决:

方式一:直接用InputStream作为方法参数

将方法参数改为InputStream,Spring会自动注入请求体对应的输入流:

@PostMapping(path = "/parse", consumes = {MediaType.APPLICATION_OCTET_STREAM_VALUE})
public String parse(@RequestBody InputStream inputStream) {
    return service.parse(inputStream);
}

方式二:用byte[]接收二进制流

如果更倾向于直接获取字节数组,可将参数设为byte[],Spring会自动完成请求体到字节数组的转换:

@PostMapping(path = "/parse", consumes = {MediaType.APPLICATION_OCTET_STREAM_VALUE})
public String parse(@RequestBody byte[] bytes) {
    try (InputStream inputStream = new ByteArrayInputStream(bytes)) {
        return service.parse(inputStream);
    } catch (IOException e) {
        throw new RuntimeException("处理输入流失败", e);
    }
}

方式三:通过HttpServletRequest获取输入流

如果需要更多请求上下文信息,可注入HttpServletRequest手动读取输入流:

@PostMapping(path = "/parse", consumes = {MediaType.APPLICATION_OCTET_STREAM_VALUE})
public String parse(HttpServletRequest request) {
    try (InputStream inputStream = request.getInputStream()) {
        return service.parse(inputStream);
    } catch (IOException e) {
        throw new RuntimeException("读取请求体失败", e);
    }
}

测试代码优化建议

你的测试代码本身无问题,但如果接口返回String类型,可显式指定Accept头匹配返回类型,避免潜在的协商问题:

mvc.perform(post("/parse")                       
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .accept(MediaType.TEXT_PLAIN)
                .content(bytes)
        ).andDo(print())
        .andExpect(status().isOk());

另外无需在Controller上添加headers = "Accept=application/octet-stream",该配置是限制请求的Accept头,与当前场景需求不符。

内容的提问来源于stack exchange,提问作者user1032836

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 21:40:33