1. 程式人生 > 實用技巧 >springboot使用RestTemplate 以及常見問題整理

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<JSONObject> 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轉換器。