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

Spring Boot RestTemplate调用接口报无匹配HttpMessageConverter错误

问题原因

异常由两个问题共同触发:

  • 请求协议使用错误:调用接口时用的是http协议,目标站点会将所有http请求302重定向到https地址,跨协议重定向不会被RestTemplate默认的请求工厂自动跟进,此时拿到的重定向响应内容类型为text/html,而RestTemplate内置的MappingJackson2HttpMessageConverter默认只支持解析application/json类型的响应,找不到匹配的消息转换器就会抛出对应异常。
  • 泛型类型传递错误:直接传入List.class作为响应类型会受Java泛型擦除机制影响,RestTemplate无法识别列表内的元素类型为Employee,即便接口正常返回JSON数据,也只会将内容解析为List<LinkedHashMap>结构,后续使用时会抛出类型转换异常。
修复方案

按以下步骤调整代码即可解决问题:

  1. 将请求地址的协议从http改为https,直接访问https接口避免触发跨协议重定向
  2. 改用exchange方法发起请求,通过ParameterizedTypeReference明确指定响应的完整泛型类型为List<Employee>,解决泛型擦除导致的反序列化问题
  3. 不要在接口方法内每次新建RestTemplate实例,提前在配置类中将其注册为Spring Bean统一注入复用,减少不必要的资源开销

修正后的代码如下:

1. RestTemplate配置类

@Configuration
public class WebConfig {
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

2. 接口方法修正

@RestController
public class UserController {
    // 注入统一配置的RestTemplate实例
    private final RestTemplate restTemplate;

    public UserController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping("/getUsers")
    public List<Employee> getUsers() {
        String resourceUrl = "https://gorest.co.in/public/v2/users";
        ResponseEntity<List<Employee>> response = restTemplate.exchange(
                resourceUrl,
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<Employee>>() {}
        );
        return response.getBody();
    }
}

补充:如果后续业务场景确实需要解析text/html类型的JSON响应,可以自定义扩展MappingJackson2HttpMessageConverter,将text/html加入其支持的MediaType列表后注册到RestTemplate中即可,本场景无需该配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 17:48:11