一、RestTemplateAutoConfiguration 增加config
@Slf4j
@Configuration
public class RestTemplateAutoConfiguration {
// 连接超时时间
private Integer connectionTimeout=5000;
// 信息读取超时时间
private Integer readTimeout=10000;
@Bean
public RestTemplate registerTemplate() {
RestTemplate restTemplate = new RestTemplate(getFactory());
// 配置消息转换器
restTemplate.setMessageConverters(getConverts());
return restTemplate;
}
// 初始化请求工厂
private SimpleClientHttpRequestFactory getFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(connectionTimeout);
factory.setReadTimeout(readTimeout);
return factory;
}
// 设置数据转换器
private List<HttpMessageConverter<?>> getConverts() {
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
// 表单转换器
FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
formConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_FORM_URLENCODED));
messageConverters.add(formConverter);
return messageConverters;
}
}
二、restTemplate 支持urlparam又支持body传参
用postman模拟请求
代码如下:
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.APPLICATION_FORM_URLENCODED;
headers.setContentType(type);
headers.setAccept(Collections.singletonList(type));
// 必须是multiValueMap,不能是map
MultiValueMap<String,Object> body = new LinkedMultiValueMap<>();
// 按照入参body所需格式拼成字符串,如果入参是图片这种格式,不能用json转化之后的jsonString,需要手动拼接字符串
String bodyValue = "{\"key1\":\"value1\"}";
body.add("bodyName",bodyValue);
HttpEntity<MultiValueMap<String,Object>> formEntity = new HttpEntity<>(body,headers);
ResponseEntity<String> responseEntity = restTemplate.exchange("https://www.ssss.com/a?b={b}&c={c}", HttpMethod.POST, formEntity, String.class, "b", "c");