<!-- 父项目配置整体依赖版本-->
<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>
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder templateBuilder){
//超时
templateBuilder.setConnectTimeout(2000).setReadTimeout(500);
return templateBuilder.build();
}
}
//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());
}
@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);
}
HttpEntity<JSONObject> entity = new HttpEntity<>(JSONObject.parseObject(content), headers);
这种情况当将请求body内容写出时是按照对象序列化的字符串内容写出,不会添加额外的引号。
springboot使用RestTemplate 以及常见问题整理
原文:https://www.cnblogs.com/fastzhe/p/13495006.html