概述
对于RESTful API,返回的一般是json字符串,如果后台想调用别人的RESTful API则需要解析json
Spring提供了更简单的方式可以自动将数据封装为对象使用
1. 摘要
- 通过RestTemplate调用REST服务
- 通过Traverson导航RESTful API
通过RestTemplate调用REST服务
1.SSL证书
注意: 对于使用SSL,启用了HTTPS则需要验证证书
简单介绍: 使用jdk的
keytool
命令创建自定义SSL证书且在本地localhost测试需要的相关配置
1.1. 相关命令
/*** 为了方便统一在jdk安装目录运行如: jdk-14.0.1\lib\security ***/
//生成服务端私钥: 别名为tomcat,文件名为mykeys.jks
keytool -keystore mykeys.jks -genkey -alias tomcat -keyalg RSA
//根据私钥导出服务端证书保存为server.crt
keytool -export -alias tomcat -keystore mykeys.jks -file server.crt
//jdk: 导入别名为tomcat的证书到cacerts中
keytool -import -v -trustcacerts -alias tomcat -file server.crt -storepass changeit -keystore cacerts
//jdk: 从cacerts中删除证书别名为tomcat
keytool -delete -alias tomcat -keystore cacerts -storepass changeit
1.2.步骤
创建
keytool -keystore mykeys.jks -genkey -alias tomcat -keyalg RSA Enter keystore password: Re-enter new password: What is your first and last name? [Unknown]: localhost What is the name of your organizational unit? [Unknown]: localhost What is the name of your organization? [Unknown]: localhost What is the name of your City or Locality? [Unknown]: localhost What is the name of your State or Province? [Unknown]: localhost What is the two-letter country code for this unit? [Unknown]: in Is CN=localhost, OU=localhost, O=localhost, L=localhost, ST=localhost, C=in correct? [no]: yes
导出
keytool -export -alias tomcat -keystore mykeys.jks -file server.crt
jdk导入
keytool -import -v -trustcacerts -alias tomcat -file server.crt -storepass changeit -keystore cacerts
2. API
方法 | 描述 |
---|---|
RestTemplate() | 构造方法 |
delete(…) | 发送DELETE请求,根据指定的URL |
exchange(…) | 根据指定的URL和请求方式发送请求,返回ResponseEntity (封装响应信息及响应体) |
execute(…) | 根据指定的URL和请求方式发送请求,将响应体封装到指定类型对象返回 |
getForEntity(…) | 发送GET请求,返回一个ResponseEntity 对象(封装了响应信息及响应体) |
getForObject(…) | 发送GET请求,将响应体封装到指定的类型对象中返回 |
headForHeaders(…) | 发送HEAD请求,返回指定URL的响应头 |
optionsForAllow(…) | 发送OPTIONS请求,返回指定URL的ALlow header |
patchForObject(…) | 发送PATCH请求,将响应体封装到指定对象中返回 |
postForEntity(…) | 发送POST请求,返回一个ResponseEntity 对象 |
postForLocation(…) | 发送POST请求,创建资源并返回资源链接 |
postForObject(…) | 发送POST请求,将响应体封装到指定类型对象中返回 |
put(…) | 根据指定的URL发送PUT请求 |
3. GET
发送GET请求获取资源
public PopInStock getPopInStockById(int id){
RestTemplate restTemplate = new RestTemplate();
PopInStock pop = null;
String url = "https://localhost:8443/api/popInStocks/{id}";
//方式一: 直接传入id
//pop = restTemplate.getForObject(url, PopInStock.class, id);
//方式二: 传入map
HashMap<String,Integer> map = new HashMap<>(1);
map.put("id",id);
//pop = restTemplate.getForObject(url,PopInStock.class,map);
//方式三: 通过URI参数
URI uri = UriComponentsBuilder.fromHttpUrl(url).build(id);
//pop = restTemplate.getForObject(uri,PopInStock.class);
//方式四: 通过getForEntity方法,返回ResponseEntity对象(记录了详细的响应信息)
ResponseEntity<PopInStock> responseEntity = restTemplate.getForEntity(url,PopInStock.class,id);
pop = responseEntity.getBody();
return pop;
}
4.PUT
发送PUT请求更新资源
*注意: * 如果开启了Spring Security的csrf防护,则需要关闭RESTful API请求的防护才行
@Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().ignoringAntMatchers("api/**"); } }
实例
//更新 public void updatePopInStock(PopInStock popInStock){ RestTemplate restTemplate = new RestTemplate(); String url = "https://localhost:8443/api/popInStocks/{id}"; restTemplate.put(url,popInStock,popInStock.getId()); }
5.DELETE
发送DELETE请求删除资源
//删除
public void deletePopInStock(int id){
RestTemplate restTemplate = new RestTemplate();
String url = "https://localhost:8443/api/popInStocks/{id}";
restTemplate.delete(url,id);
}
6.POST
发送POST请求新增资源
//新增
public PopInStock createPopInStock(PopInStock popInStock){
RestTemplate restTemplate = new RestTemplate();
String url = "https://localhost:8443/api/popInStocks";
return restTemplate.postForObject(url,popInStock,PopInStock.class);
}
public URI createPopInStockLocation(PopInStock popInStock){
RestTemplate restTemplate = new RestTemplate();
String url = "https://localhost:8443/api/popInStocks";
return restTemplate.postForLocation(url,popInStock);
}
public PopInStock createPopInStockEntity(PopInStock popInStock){
RestTemplate restTemplate = new RestTemplate();
String url = "https://localhost:8443/api/popInStocks";
ResponseEntity<PopInStock> responseEntity = restTemplate.postForEntity(url,popInStock,PopInStock.class);
return responseEntity.getBody();
}
通过Traverson导航RESTful API
Traverson
是 Spring Data HATEOAS提供的用于方便导航RESTful API,即根据返回的json通过其字段名即可导航到其值Traverson
只能导航到连接进行查询操作,对于POST PUT DELETE操作须使用RestTemplate
实例
public void traverson(){
//创建Traverson
Traverson traverson = new Traverson(URI.create("https://localhost:8443/api"), MediaTypes.HAL_JSON);
//获取PopInStocks
ParameterizedTypeReference<CollectionModel<PopInStock>> popInStocksType = new ParameterizedTypeReference<>(){};
/** 1 **/
CollectionModel<PopInStock> popInStocks = traverson.follow("pops")//根据json字段名
.toObject(popInStocksType);//因为泛型擦除的特性,无法传入正常的泛型类型,因此需要通过ParameterizedTypeReference
assert popInStocks != null;
//获取结果集
Collection<PopInStock> collection = popInStocks.getContent();
/** 2 **/
Collection<PopInStock> recents = traverson.follow("pops","recents") //等价于follow("pops").follow("recents")
.toObject(popInStocksType).getContent();
/** 3 **/
//获取对应的url
String url = traverson.follow("pops").asLink().getHref();
//再使用RestTemplate插入数据
PopInStock popInStock = new PopInStock();
popInStock.setName("Traverson");
new RestTemplate().postForEntity(url,popInStock,PopInStock.class);
}