参考:【B站视频】Java Web 编程 之 RestTemplate 实战全集 & SpringBoot & Spring 框架集成
Springboot整合RestTemplate、java调用http请求方式、
RestTemplate工具类,支持http和https请求以及http携带body请求
第一步、定义一个配置类
package com.tj.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* HTTP请求模版
*/
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
/**
默认底层执行 HttpURLConnection
可以指定如下不同的类
Apache HttpComponentsClientHttpRequestFactory()
Netty Netty4ClientHttpRequestFactory()
OkHttp OkHttp3ClientHttpRequestFactory()
*/
return new RestTemplate();
}
}
如果不定义配置类,也可以通过new RestTemplate()直接使用
HttpGet请求介绍
//可以获取对象
restTemplate.getForObject();
//不仅可以获取对象,还可以获取http状态码,请求头等详细信息
restTemplate.getForEntity();
使用案例getForObject
@Autowired
private RestTemplate restTemplate;
@Autowired
private BaseNumvarService baseNumvarService;
@Test
public void testGetForObject() {
String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={ID}&corpsecret={SECRET}";
String corpid = baseNumvarService.getCorpid();
String secret_txl = baseNumvarService.getSecret_txl();
HashMap<String, String> map = MapUtils.newHashMap();
map.put("ID", corpid);
map.put("SECRET", secret_txl);
/**
第一个参数:请求地址
第二个参数:返回值类型
第三个参数:请求携带的参数,注意,map里的字段要和url里的占位符字符对应
*/
Map<String, Object> res = restTemplate.getForObject(url,Map.class,map);
log.info(res.toString());
}
使用案例GetForEntity
@Autowired
private RestTemplate restTemplate;
@Autowired
private BaseNumvarService baseNumvarService;
@Test
public void testGetForEntity() {
String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={ID}&corpsecret={SECRET}";
HashMap<String, String> map = MapUtils.newHashMap();
map.put("ID", baseNumvarService.getCorpid());
map.put("SECRET", baseNumvarService.getSecret_txl());
/**
第一个参数:请求地址
第二个参数:返回值类型
第三个参数:请求携带的参数,注意,map里的字段要和url里的占位符字符对应
*/
ResponseEntity<HashMap> entity = restTemplate.getForEntity(url, HashMap.class, map);
//返回状态码
int statusCodeValue = entity.getStatusCodeValue();
log.info("状态码:{}", statusCodeValue);
//http返回头
HttpHeaders headers = entity.getHeaders();
log.info("http返回头:{}", headers);
//返回对应的请求结果
HashMap body = entity.getBody();
log.info("请求结果:{}", body);
}
HttpPOST请求介绍
RestTemplate的POST方法与Get方法的区别是post方法传参数Map必须是MultiValueMap
Post方法的MultiValueMap既支持基本类型分开传参,也支持实体传参。类似下面的形式
JSON请求
参数1:请求地址
参数2:可以是java对象,JSON字符串
参数3:返回值的类型
@Test
public void testPostForObject() {
String secretCheckin = baseNumvarService.getSecretCheckin();
String token = baseNumvarService.getAccessTokenBySecret(secretCheckin);
String url = "https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckindata?access_token=" + token;
String json = "{\n" +
" \"opencheckindatatype\": 3,\n" +
" \"starttime\": 1654088401,\n" +
" \"endtime\": 1654520401,\n" +
" \"useridlist\": [\"a00000000XingXianXiaoLiMuYe13753\"]" +
"}";
//POST请求
Map map = restTemplate.postForObject(url, json, Map.class);
log.info(map.toString());
}