springboot中RestTemplate 的getForObject 报错ClassCastException错误

1、getForObject的定义如下:

    public <T> T getForObject(URI url, Class<T> responseType) throws RestClientException {
        RequestCallback requestCallback = this.acceptHeaderRequestCallback(responseType);
        HttpMessageConverterExtractor<T> responseExtractor = new HttpMessageConverterExtractor(responseType, this.getMessageConverters(), this.logger);
        return this.execute(url, HttpMethod.GET, requestCallback, responseExtractor);
    }

当responseType的泛型T中包含 List 的时候,结果无法转换成 List,这时候便会包ClassCastException 错误

 

2、解决方案

使用 exchange() 方法代替 getForObject

示例:RegulateCommand 为带有 List 的类

RegulateCommand regulateCommandResult = restTemplate.exchange(customConfig.getBaseUrl() + "/sws/regulate_pressure/executing",
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<RegulateCommand>() {}).getBody();

 

上一篇:Ajax 下载文件 文件被损坏


下一篇:RestTemplate post请求使用map传参 Controller 接收不到值的解决方案 postForObject方法源码解析.md