springboot-resttemplate2

RestTemplate是RestOperations的实现类,实现了Get、Post、Put、Delete等请求。

  • Get

    get请求有2中,getforentity和getforobject,2个方法的内部实现基本相同,不同在于返回值,一个返回ResponseEntity(包含body、header、status),一个只返回了body;

1
2
3
<T> ResponseEntity<T> (String var1, Class<T> var2, Object... var3) throws RestClientException;
<T> ResponseEntity<T> (String var1, Class<T> var2, Map<String, ?> var3) throws RestClientException;
<T> ResponseEntity<T> (URI var1, Class<T> var2) throws RestClientException;
1
2
3
<T> T getForObject(String var1, Class<T> var2, Object... var3) throws RestClientException;
<T> T getForObject(String var1, Class<T> var2, Map<String, ?> var3) throws RestClientException;
<T> T getForObject(URI var1, Class<T> var2) throws RestClientException;

另外,每个请求有3中重载方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14

String url = "https://story.hhui.top/detail?id=666106231640";
InnerRes res = restTemplate.getForObject(url, InnerRes.class);
// 使用方法一,传参替换
url = "https://story.hhui.top/detail?id={?}";
res = restTemplate.getForObject(url, InnerRes.class, "666106231640");
// 使用方法二,map传参
url = "https://story.hhui.top/detail?id={id}";
Map<String, Object> params = new HashMap<>();
params.put("id", 666106231640L);
res = restTemplate.getForObject(url, InnerRes.class, params);
// 使用方法三,URI访问
URI uri = URI.create("https://story.hhui.top/detail?id=666106231640");
res = restTemplate.getForObject(uri, InnerRes.class);
  • Post

    post 请求除了object和entity外,还有一个location的方法·

1
2
3
4
5
6

public URI postForLocation(String url, @Nullable Object request, Object... uriVariables) throws RestClientException {
RequestCallback requestCallback = this.httpEntityCallback(request);
HttpHeaders headers = (HttpHeaders)this.execute(url, HttpMethod.POST, requestCallback, this.headersExtractor(), uriVariables);
return headers != null ? headers.getLocation() : null;
}

一般登录or注册都是post请求,而这些操作完成之后呢?大部分都是跳转到别的页面去了,这种场景下,就可以使用 postForLocation 了,提交数据,并获取返回的URI