WebClient调用接口始终返回UnsupportedMediaTypeException求助
问题分析与解决方案
异常原因
你遇到的UnsupportedMediaTypeException核心原因:
- 你的WebClient请求通过
.accept(MediaType.APPLICATION_JSON)声明了希望接收JSON格式响应,但服务端实际返回的响应头Content-Type为application/octet-stream - WebClient的
MappingJackson2HttpMessageConverter仅能处理Content-Type为application/json类的JSON类型响应,无法识别application/octet-stream类型内容并转换为MonoResponseDto对象 - 转换为
String时,StringHttpMessageConverter支持绝大多数媒体类型,因此可以正常获取响应内容
问题根源(服务端)
你的ConsentController返回ResponseEntity<Consent>时,未明确指定响应媒体类型,本地环境下Spring MVC未自动设置正确的Content-Type: application/json,导致响应被标记为application/octet-stream。
解决方案
方案1:修复服务端控制器(推荐)
在@GetMapping注解中明确指定响应媒体类型:
@RestController @RequestMapping("/v2/consent") public class ConsentController { @Autowired private ConsentService consentService; @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Consent> getConsent(){ return new ResponseEntity<>(consentService.getConsent(), HttpStatus.OK); } }
或手动在ResponseEntity中设置响应头:
@GetMapping() public ResponseEntity<Consent> getConsent(){ HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return new ResponseEntity<>(consentService.getConsent(), headers, HttpStatus.OK); }
方案2:客户端兼容处理(临时 workaround)
如果暂时无法修改服务端,可调整WebClient的消息转换器,让它把application/octet-stream类型响应当作JSON处理:
WebClient webClient = WebClient.builder() .exchangeStrategies(ExchangeStrategies.builder() .codecs(configurer -> { // 让Jackson解码器同时支持application/octet-stream类型 configurer.defaultCodecs().jackson2JsonDecoder( new Jackson2JsonDecoder(new ObjectMapper(), MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM) ); }) .build()) .build();
补充说明
.accept()方法仅用于设置请求头的Accept字段,告知服务端客户端期望的响应类型,无法强制服务端返回指定类型。问题本质是服务端返回的响应媒体类型不符合预期,优先修复服务端是更规范的做法。
内容的提问来源于stack exchange,提问作者hyperFlash
相关产品推荐
相关产品推荐

