RestTemplate远程调用响应类型错误

目录

1.问题详情

2.问题原因

3.解决办法


1.问题详情

 Could not extract response: no suitable HttpMessageConverter found for response type [class com.hhmt.delivery.utils.response.ocpx.MeiTunVo] and content type [text/html;charset=UTF-8]

2.问题原因

响应数据绑定时候不支持Content-type text/html这种格式,一般支持json

3.解决办法

package com.hhmt.delivery.config;

import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.util.ArrayList;
import java.util.List;

/**
 * 辉煌明天
 * FileName: WxMappingJackson2HttpMessageConverter
 * <p>
 * Author:   huachun
 * email: huachun_w@163.com
 * Date:     2021/11/18 17:44
 * Description:
 */
public class WxMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {

    /**
     * @Description: 处理常见的响应Content-type问题
     * 例如:响应Content-type:text/html 无法正常绑定到响应类中
     * 详情参考:https://blog.csdn.net/qq_23888451/article/details/84637956
     * @Author: huachun
     * @Date: 2021/11/18 18:24
     * @return: null
     **/
    public WxMappingJackson2HttpMessageConverter() {
        List<MediaType> mediaTypes = new ArrayList<>();
        mediaTypes.add(MediaType.TEXT_PLAIN);
        mediaTypes.add(MediaType.TEXT_HTML);  //加入text/html类型的支持
        setSupportedMediaTypes(mediaTypes);// tag6
    }
}

在使用之前进行添加

restTemplate.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());
            ResponseEntity<MeiTunVo> response = restTemplate.getForEntity(meituanUrl, MeiTunVo.class, entry);

这样就不会报错了

4.常见转换问题

响应时类型转换错误

通过下面调用restTemplate调用出现了下面异常提示

restTemplate.getForObject(realUrl, QuickViewVo.class);
org.springframework.web.client.RestClientException: Error while extracting response for type [class com.hhmt.delivery.ocpx.bean.ResultVo] and content type [text/html]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected character ('<' (code 60)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
 at [Source: (PushbackInputStream); line: 1, column: 2] 
 
 
 Caused by: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected character ('<' (code 60)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
 at [Source: (PushbackInputStream); line: 1, column: 2]
	at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:285) ~[spring-web-5.2.11.RELEASE.jar:5.2.11.RELEASE]
	at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:243) ~[spring-web-5.2.11.RELEASE.jar:5.2.11.RELEASE]
	at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:105) ~[spring-web-5.2.11.RELEASE.jar:5.2.11.RELEASE]
	... 111 common frames omitted
Caused by: com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
 at [Source: (PushbackInputStream); line: 1, column: 2]

将响应类型改为String

restTemplate.getForObject(realUrl, String.class);

得到的结果如下(如果响应类不改变,在postman调用是正常返回的) 

<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>openresty</center>
</body>
</html>

问题原因:

解决方法:

HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
            HttpClient httpClient = HttpClientBuilder.create()
                    .setRedirectStrategy(new LaxRedirectStrategy())
                    .build();
            factory.setHttpClient(httpClient);

            restTemplate.setRequestFactory(factory);

原文参考:使用RestTemplate报301 Moved Permanently解决_Lihaitao-CSDN博客_resttemplate请求返回301

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你好!关于使用RestTemplate进行远程调用,我可以给你一些帮助。RestTemplate是Spring框架提供的一个用于发送HTTP请求的客户端工具。你可以使用它来调用其他系统的RESTful API。 首先,你需要在你的项目中导入RestTemplate的依赖。如果你使用的是Maven,可以在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 接下来,你可以在你的代码中使用RestTemplate来发送HTTP请求。下面是一个简单的示例: ```java import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; public class RemoteServiceClient { public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); String url = "http://example.com/api/endpoint"; ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, String.class); String responseBody = response.getBody(); System.out.println(responseBody); } } ``` 在上面的示例中,我们创建了一个RestTemplate实例,并使用exchange()方法发送了一个GET请求。你可以根据需要选择合适的HTTP方法(如GET、POST、PUT等)和请求体内容。 当然,在实际应用中,你可能还需要处理错误、设置请求头、传递URL参数等。RestTemplate提供了一些其他的方法和功能来满足这些需求。如果你需要更多细节或更复杂的使用场景,可以查阅Spring官方文档或其他相关资源。 希望这些信息对你有所帮助!如果你有任何其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值