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);
}
- 當配置了以上http轉換器,發送string內容時,會給字符串添加對應的雙引號,發送到對端時解析會出現問題。
解決方法
- 將對應的字符串轉換成json類型,發送
HttpEntity<JSONObject> entity = new HttpEntity<>(JSONObject.parseObject(content), headers);
這種情況當將請求body內容寫出時是按照對象序列化的字符串內容寫出,不會添加額外的引號。
- 去掉fastjson http轉換器。