springboot使用RestTemplate 以及常见问题整理

springboot使用RestTemplate

maven配置

父项目配置版本依赖

  <!-- 父项目配置整体依赖版本-->  				
          <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.0.4.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

子项目直接使用


 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

代码配置RestTemplate bean

    
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder templateBuilder){
        //超时
        templateBuilder.setConnectTimeout(2000).setReadTimeout(500);
        return templateBuilder.build();
    }
}
 	

踩坑

问题: 服务端报body域中的json解析失败

使用代码如下

//basic authorization
String authorization = Base64.getEncoder().encodeToString((commonServicePlateform_username + ":" + commonServicePlateform_password).getBytes(Charset.forName("UTF-8")));
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + authorization);
        //主要类型为json,因此需要注意。
        headers.add("Content-Type", "application/json");
        String content = generateBody();
        //注意:content为json字符串
        HttpEntity<String> entity = new HttpEntity<>(content, headers);
        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(commonServicePlateform_url, entity, JSONObject.class);
        if (responseEntity.getStatusCode().value() == 200) {
            JSONObject body = responseEntity.getBody();
            if (body.getBoolean("result")) {
                log.info("推送成功:  {}", body.getString("message"));
            } else {
                log.info("推送失败:  {}", body.getString("message"));
            }
        } else {
            log.error("推送失败 {}", responseEntity.getStatusCodeValue());
        }

实际分析问题发现,因为配置了FastJsonHttpMessageConverter

  @Bean
    public HttpMessageConverters fastJsonConfigure() {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //,SerializerFeature.DisableCheckSpecialChar
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
        //日期格式化
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        converter.setFastJsonConfig(fastJsonConfig);
        return new HttpMessageConverters(converter);
    }
  1. 当配置了以上http转换器,发送string内容时,会给字符串添加对应的双引号,发送到对端时解析会出现问题。

解决方法

  1. 将对应的字符串转换成json类型,发送HttpEntity<JSONObject> entity = new HttpEntity<>(JSONObject.parseObject(content), headers);

这种情况当将请求body内容写出时是按照对象序列化的字符串内容写出,不会添加额外的引号。

  1. 去掉fastjson http转换器。
posted @ 2020-08-13 10:41  bendandan  阅读(3062)  评论(0编辑  收藏  举报