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

RestTemplate请求S3上的JSON文件报binary/octet-stream转换错误如何解决

该问题完全和content-type相关,具体原因和解决方案如下:

问题根因

你请求的S3资源返回的响应头Content-Type值为binary/octet-stream,而Spring RestTemplate默认的MappingJackson2HttpMessageConverter(负责JSON反序列化的消息转换器)仅支持application/json、application/*+json这类标准JSON内容类型,找不到匹配的转换器就会抛出你遇到的异常。
你用Postman调用本地接口正常,是因为你发POST请求时主动设置了请求头Content-Type: application/json,符合本地接口消息转换器的识别规则。

解决方案

可以选择以下任意一种方式解决:

方案1:扩展JSON消息转换器支持的媒体类型(推荐,全局生效一次配置即可)

给RestTemplate的Jackson消息转换器添加对binary/octet-stream的支持,配置代码示例:

import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import java.util.Arrays;

// 初始化自定义Jackson转换器
MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter();
jacksonConverter.setSupportedMediaTypes(Arrays.asList(
    MediaType.APPLICATION_JSON,
    MediaType.APPLICATION_OCTET_STREAM // 对应binary/octet-stream类型
));
// 将自定义转换器添加到RestTemplate的转换器列表首位,优先匹配
restTemplate.getMessageConverters().add(0, jacksonConverter);

配置完成后再调用getForObject即可正常反序列化。

方案2:手动转换响应结果(适合临时调用场景,不需要全局修改配置)

先把响应结果读取为字符串,再手动用ObjectMapper转成目标对象数组,代码示例:

import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpMethod;
import com.fasterxml.jackson.databind.ObjectMapper;

ResponseEntity<String> rawResponse = restTemplate.exchange(URL, HttpMethod.GET, null, String.class);
ObjectMapper objectMapper = new ObjectMapper();
ProductModel[] books = objectMapper.readValue(rawResponse.getBody(), ProductModel[].class);

额外注意事项

你当前定义的ProductModel中retail_price和discounted_price为基础类型int,如果返回的JSON中对应字段存在null值会导致反序列化失败,建议修改为包装类型Integer。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 02:06:03