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

调用Spring REST接口时出现415不支持application/octet-stream类型错误

解决Spring REST API 415 Unsupported Media Type错误

针对你遇到的Content type 'application/octet-stream' not supported错误,可按以下步骤排查解决:

1. 校验请求各Part的Content-Type设置

你的接口要求消费multipart/form-data,但请求中某个Part的Content-Type不符合Spring的解析要求:

  • requestBody部分:必须设置为application/json,因为Spring需要将其解析为MyClass对象。如果客户端未指定该Part的Content-Type,Spring可能会默认按application/octet-stream处理,导致解析失败。
  • file部分:确保文件Part的Content-Type与实际文件类型匹配(如image/jpeg、application/pdf),部分客户端在未指定时会使用application/octet-stream,这也可能触发错误。

2. 允许文件Part接受application/octet-stream

如果需要支持上传application/octet-stream类型的文件,可在@RequestPart注解中明确指定允许的Content-Type:

@Valid @NotNull @RequestPart(value = "file", contentType = {"application/octet-stream", "multipart/form-data"}) MultipartFile file

3. 修正客户端请求构造方式

  • Swagger/Postman调用:
    • requestBody选择raw格式并指定为JSON,同时在请求头(或Part的Content-Type)设置application/json;
    • file部分选择文件后,确认自动填充的Content-Type正确,若未填充可手动指定。
  • 代码调用(如RestTemplate):
    构造请求时为每个Part设置正确的Content-Type:
    MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>();
    
    // 为JSON请求体设置Content-Type
    HttpHeaders jsonHeaders = new HttpHeaders();
    jsonHeaders.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<MyClass> jsonPart = new HttpEntity<>(new MyClass(), jsonHeaders);
    requestBody.add("requestBody", jsonPart);
    
    // 为文件设置Content-Type(支持octet-stream)
    HttpHeaders fileHeaders = new HttpHeaders();
    fileHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    HttpEntity<FileSystemResource> filePart = new HttpEntity<>(new FileSystemResource(new File("test.file")), fileHeaders);
    requestBody.add("file", filePart);
    
    ResponseEntity<DocumentBaseResponse> response = restTemplate.postForEntity("/test", requestBody, DocumentBaseResponse.class);
    

4. 检查Spring消息转换器配置

确保Spring已正确配置MappingJackson2HttpMessageConverter(Spring Boot默认已配置),该转换器负责将JSON请求体解析为Java对象。若自定义了WebMvc配置,需保证未移除该转换器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 09:47:30