//设置请求头
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// 封装参数
MultiValueMap<String, String> param = new LinkedMultiValueMap<>();
//添加请求的参数
param.add("key", "value");
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(param, header);
// 执行HTTP请求
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
if (response.getStatusCodeValue() == 200){
String body = response.getBody();
if(body != null){
JSONObject jsonObject = JSON.parseObject(body);
Object access_token = jsonObject.get("access_token");
token = (String) access_token;
}
}else {
log.warn("请求异常");
}
实例化 RestTemplate
@Bean
public RestTemplate initRestTemplate(){
return new RestTemplate();
}