在系列四中讲解Ribbon时使用了RestTemplate对象。该对象会使用Ribbon的自动化配置,并同时配置@LoadBalanced还能够开启客户端负载均衡。下面介绍一下RestTemplate针对不同请求类型和参数类型的使用。
GET请求
在RestTemplate中对GET请求可以通过如下两种方式实现。
第一种,getForEntity函数。该方法返回的是ResponseEntity,该对象是Spring对Http请求响应的封装。其中主要存储了HTTP的几个重要元素,比如HTTP请求状态码的枚举对象HttpStatus(我们常说的404,500)、在他的父类HttpEntity中还存储着HTTP请求的头信息对象HttpHeaders以及泛型类型的请求体对象(响应码、contentType、contentLength、响应消息体等)。
常用方式
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/user1?name={1}", String.class,"xiaoming");
String body = responseEntity.getBody();
//返回对象格式
ResponseEntity<User> responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/user2?name={1}&age={2}", User.class,"xiaoming",22);
User user = responseEntity.getBody();
getForEntity函数提供了三种重载方法
1.getForEntity(String url,Class responseType,Object...urlVariables)
该方法提供了三个参数,第一个参数url为请求的地址,第二个参数responseType是请求响应体body的包装类型,urlVariables为url中的参数绑定。get请求参数可以拼接到url后面,例如:http:ip//xxx/xx?username=xxx,但是更好的方式是使用占位符并配合urlVariables参数实现get请求参数的绑定。注意因为urlVariables是一个数组,所以它的顺序会对应url值占位符的数字顺序。当然你也可以使用json字符串的形式:
ResponseEntity<User> responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/user3?jsonStr={jsonStr}", User.class,"{\"name\":\"xiaoming\",\"age\":\"22\"}");
User user = responseEntity.getBody();
2.getForEntity(String url,Class responseType,Map urlVariables)
这里urlVariables参数类型是Map,所以在使用该方法进行参数绑定时必须在占位符中指定Map中参数的key值。
Map<String,Object> params = new HashMap<String,Object>();
params.put("name", "xiaoming");
params.put("age", 22);
ResponseEntity<User> responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/user2?name={name}&age={age}", User.class,params);
User user = responseEntity.getBody();
3.getForEntity(URI uri,Class responseType)
该方法使用URI对象来替代之前的url和urlVariables参数来指定访问地址和参数绑定。URI是JDK java.net包下的类,他表示一个统一资源标识符引用。
UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://HELLO-SERVICE/user1?name={name}").build().expand("xiaoming").encode();
URI uri = uriComponents.toUri();
ResponseEntity<String> responseEntity = restTemplate.getForEntity(uri, String.class);
String body = responseEntity.getBody();
第二种,getForObject函数,该方法可以理解为getForEntity函数的进一步封装。它通过HttpMessageConverterExtractor对HTTP的请求响应体body内容进行对象转换,实现请求直接返回包装好的对象内容,该函数少了一步获取body的步骤所以更方便。比如:
String result = restTemplate.getForObject("http://HELLO-SERVICE/user1?name={1}",String.class,"xiaoming");
//返回对象格式
User user = restTemplate.getForObject("http://HELLO-SERVICE/user2?name={1}&age={2}", User.class, "xiaoming",22);
getForObject函数也提供了三种重载方法,参数类似于上面介绍的三个。
1.getForObject(String url,Class responseType,Object...urlVariables)
2.getForObject(String url,Class responseType,Map urlVariables)
3.getForObject(URI uri,Class responseType)
POST请求
在RestTemplate中,对POST请求可以通过如下三个方法进行调用实现。
第一种:postForEntity函数。该方法同GET请求中的getForEntity类似,会在调用后返回ResponseEntity<T>对象,其中T为请求响应的body类型。比如:
User user = new User("xiaoming",22);
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://HELLO-SERVICE/user4", user, String.class);
String body = responseEntity.getBody();
postForEntity函数也实现了三种重载方法
1.postForEntity(String url,Object request,Class responseType,Object...urlVariables)
2.postForEntity(String url,Object request,Class responseType,Map urlVariables)
3.postForEntity(URI uri,Object request,Class responseType)
这些函数中的参数方法大部分与getForEntity一致,需要注意的是新加的request参数,该参数可以是一个普通对象,也可以是一个HttpEntity对象。如果是一个普通对象,而非HttpEntity对象的时候,RestTemplate会将请求对象转换为一个HttpEntity对象来处理,其中Object就是request的类型,request内容会被视作完整的body来处理;而如果request是一个HttpEntity对象,那么就会被当作一个完整的HTTP请求对象来处理,这个request中不仅包含了body的内容也包含了header的内容。
HttpHeaders headers = new HttpHeaders();
headers.add("token", "xxxxxxxxxxx");
HttpEntity httpEntity = new HttpEntity(headers);
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("age", "33");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<User> responseEntity = restTemplate.postForEntity("http://HELLO-SERVICE/user5", request, User.class);
String body = responseEntity.getBody().toString();
第二种,postForObject函数。该方法和getForObject类似,它的作用是简化postForEntity的后续处理。通过直接将请求响应的body内容包装成对象来使用。
User user = new User("xiaoming",22);
String body = restTemplate.postForObject("http://HELLO-SERVICE/user4", user, String.class);
postForObject函数也实现了三种重载方法,可以参考get请求的getForObject
1.postForObject(String url,Object request,Class responseType,Object...urlVariables)
2.postForObject(String url,Object request,Class responseType,Map urlVariables)
3.postForObject(URI uri,Object request,Class responseType)
第三种,postForLocation函数。该方法实现了以POST请求提交资源,并返回新资源的URI。
User user = new User("xiaoming",22);
URI uri = restTemplate.postForLocation("http://HELLO-SERVICE/user", user);
postForLocation函数也实现了三种重载方法,可以参考get请求的getForObject
1.postForLocation(String url,Object request,Object...urlVariables)
2.postForLocation(String url,Object request,Map urlVariables)
3.postForLocation(URI uri,Object request)
由于postForLocation函数会返回新资源的URI,该URI就相当于指定返回类型,所以此方法实现的POST请求不需要像postForEntity和postForObject那样指定responseType。
PUT请求
int id = 1;
User user = new User("xiaoming",22);
restTemplate.put("http://HELLO-SERVICE/user6/{1}", user, id);
put函数也实现了三种重载方法
1.put(String url,Object request,Object...urlVariables)
2.put(String url,Object request,Map urlVariables)
3.put(URI uri,Object request)
put方法返回类型为void,所以没有返回值。
DELETE请求
int id = 1;
restTemplate.delete("http://HELLO-SERVICE/user7/{1}",id);
delete函数也实现了三种重载方法
1.delete(String url,Object...urlVariables)
2.delete(String url,Map urlVariables)
3.delete(URI uri)
由于我们进行REST请求时,通常将DELETE请求的唯一标识拼接在url中,所以DELETE请求也不需要request的body信息。
exchange()函数
当然也可以用统一的模板进行四中方式的请求
restTemplate.exchange(
String url,
HttpMethod method,
HttpEntity requestEntity,
Class responseType,
Object uriVariables[]
)
1)url: 请求地址;
2)method: 请求类型(如:POST,PUT,DELETE,GET);
3)requestEntity: 请求实体,封装请求头,请求内容
4)responseType: 响应类型,根据服务接口的返回类型决定
5)uriVariables: url中参数变量值
POST请求
String params= "{\"name\":\"小明\",\"age\":33}";
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
HttpEntity<String> entity = new HttpEntity<String>(params,headers);
ResponseEntity<User> resp = restTemplate.exchange("http://HELLO-SERVICE/user9", HttpMethod.POST, entity, User.class);
PUT请求
String params= "{\"name\":\"小明\",\"age\":33}";
HttpHeaders headers = new HttpHeaders();
//乱码
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
HttpEntity<String> entity = new HttpEntity<String>(params,headers);
ResponseEntity<String> resp = restTemplate.exchange("http://HELLO-SERVICE/user10", HttpMethod.PUT, entity, String.class);
DELETE请求
ResponseEntity<String> resp = restTemplate.exchange("http://HELLO-SERVICE/user11/{1}", HttpMethod.DELETE, null, String.class,1);
GET请求
ResponseEntity<User> resp = restTemplate.exchange("http://HELLO-SERVICE/user8?jsonStr={jsonStr}", HttpMethod.GET, null, User.class,"{\"name\":\"xiaoming\",\"age\":33}");
如果返回复杂的数据比如数组或list需要用下面的方式
StringBuilder sb = new StringBuilder();
ResponseEntity<User[]> resp = restTemplate.exchange("http://HELLO-SERVICE/user12?jsonStr={jsonStr}", HttpMethod.GET, null, User[].class,"{\"name\":\"xiaoming\",\"age\":33}");
for(User user : resp.getBody()){
sb.append(user.toString()+"<br>");
}
StringBuilder sb = new StringBuilder();
ParameterizedTypeReference<List<User>> res = new ParameterizedTypeReference<List<User>>(){};
ResponseEntity<List<User>> resp = restTemplate.exchange("http://HELLO-SERVICE/user13?jsonStr={jsonStr}", HttpMethod.GET, null, res,"{\"name\":\"xiaoming\",\"age\":33}");
for(User user : resp.getBody()){
sb.append(user.toString()+"<br>");
}
对于返回属性中有范型数据的复合对象,比如分页对象
ResponseEntity<String> results = restTemplate.exchange(url,HttpMethod.GET, null, String.class, params);
// 借助com.fasterxml.jackson.databind.ObjectMapper 对象来解析嵌套的json字符串
ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
PageInfo<Product> page = mapper.readValue(results.getBody(), new TypeReference<PageInfo<Product>>() { });
最后附上代码
消费者代码
package com.wya.springboot.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class RestTemplateController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("restTemplate1")
public String rest1(){
ResponseEntity<String> responseEntity =
restTemplate.getForEntity("http://HELLO-SERVICE/user1?name={1}", String.class,"xiaoming");
String body = responseEntity.getBody();
return body;
}
@GetMapping("restTemplate2")
public String rest2(){
ResponseEntity<User> responseEntity =
restTemplate.getForEntity("http://HELLO-SERVICE/user2?name={1}&age={2}", User.class,"xiaoming",22);
User user = responseEntity.getBody();
return user.toString();
}
@GetMapping("restTemplate3")
public String rest3(){
ResponseEntity<User> responseEntity =
restTemplate.getForEntity("http://HELLO-SERVICE/user3?jsonStr={jsonStr}", User.class,"{\"name\":\"xiaoming\",\"age\":22}");
User user = responseEntity.getBody();
return user.toString();
}
@GetMapping("restTemplate4")
public String rest4(){
String result = restTemplate.getForObject("http://HELLO-SERVICE/user1?name={1}",String.class,"xiaoming");
return result;
}
@GetMapping("restTemplate5")
public String rest5(){
User user = restTemplate.getForObject("http://HELLO-SERVICE/user2?name={1}&age={2}", User.class, "xiaoming",22);
return user.toString();
}
@GetMapping("restTemplate6")
public String rest6(){
User user = new User("xiaoming",22);
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://HELLO-SERVICE/user4", user, String.class);
return responseEntity.getBody();
}
@GetMapping("restTemplate7")
public String rest7(){
HttpHeaders headers = new HttpHeaders();
headers.add("token", "xxxxxxxxxxx");
HttpEntity httpEntity = new HttpEntity(headers);
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("age", "33");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<User> responseEntity = restTemplate.postForEntity("http://HELLO-SERVICE/user5", request, User.class);
String body = responseEntity.getBody().toString();
return body;
}
@GetMapping("restTemplate8")
public String rest8(){
User user = new User("xiaoming",22);
String body = restTemplate.postForObject("http://HELLO-SERVICE/user4", user, String.class);
return body;
}
@GetMapping("restTemplate9")
public String rest9(){
int id = 1;
User user = new User("xiaoming",22);
restTemplate.put("http://HELLO-SERVICE/user6/{1}", user, id);
return "success";
}
@GetMapping("restTemplate10")
public String rest10(){
int id = 1;
restTemplate.delete("http://HELLO-SERVICE/user7/{1}",id);
return "success";
}
@GetMapping("restTemplate11")
public String rest11(){
ResponseEntity<User> resp = restTemplate.exchange("http://HELLO-SERVICE/user8?jsonStr={jsonStr}", HttpMethod.GET, null, User.class,"{\"name\":\"xiaoming\",\"age\":33}");
return resp.getBody().toString();
}
@GetMapping("restTemplate12")
public String rest12(){
String params= "{\"name\":\"小明\",\"age\":33}";
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
HttpEntity<String> entity = new HttpEntity<String>(params,headers);
ResponseEntity<User> resp = restTemplate.exchange("http://HELLO-SERVICE/user9", HttpMethod.POST, entity, User.class);
return resp.getBody().toString();
}
@GetMapping("restTemplate13")
public String rest13(){
String params= "{\"name\":\"小明\",\"age\":33}";
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
HttpEntity<String> entity = new HttpEntity<String>(params,headers);
ResponseEntity<String> resp = restTemplate.exchange("http://HELLO-SERVICE/user10", HttpMethod.PUT, entity, String.class);
return resp.getBody();
}
@GetMapping("restTemplate14")
public String rest14(){
ResponseEntity<String> resp = restTemplate.exchange("http://HELLO-SERVICE/user11/{1}", HttpMethod.DELETE, null, String.class,1);
return resp.getBody();
}
@GetMapping("restTemplate15")
public String rest15(){
StringBuilder sb = new StringBuilder();
ResponseEntity<User[]> resp = restTemplate.exchange("http://HELLO-SERVICE/user12?jsonStr={jsonStr}", HttpMethod.GET, null, User[].class,"{\"name\":\"xiaoming\",\"age\":33}");
for(User user : resp.getBody()){
sb.append(user.toString()+"<br>");
}
return sb.toString();
}
@GetMapping("restTemplate16")
public String rest16(){
StringBuilder sb = new StringBuilder();
ParameterizedTypeReference<List<User>> res = new ParameterizedTypeReference<List<User>>(){};
ResponseEntity<List<User>> resp = restTemplate.exchange("http://HELLO-SERVICE/user13?jsonStr={jsonStr}", HttpMethod.GET, null, res,"{\"name\":\"xiaoming\",\"age\":33}");
for(User user : resp.getBody()){
sb.append(user.toString()+"<br>");
}
return sb.toString();
}
}
服务提供者代码
package com.wya.springboot.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
@RestController
public class UserController {
@GetMapping("user1")
public String user1(String name){
return name+",21";
}
@GetMapping("user2")
public User user2(String name,int age){
return new User(name, age);
}
@GetMapping("user3")
public User user3(String jsonStr){
JSONObject user = JSONObject.parseObject(jsonStr);
String name = user.getString("name");
int age = user.getIntValue("age");
return new User(name, age);
}
@PostMapping("user4")
public String user4(@RequestBody User user){
return user.toString();
}
@PostMapping("user5")
public User user5(int age,HttpServletRequest request){
String token = request.getHeader("token");
return new User(token,age);
}
@PutMapping("user6/{id}")
public String user6(@PathVariable("id") int id,@RequestBody User user){
System.out.println(id+","+user.toString());
return user.toString();
}
@DeleteMapping("user7/{id}")
public void user7(@PathVariable("id") int id){
System.out.println(id);
}
@GetMapping("user8")
public User user8(String jsonStr){
JSONObject user = JSONObject.parseObject(jsonStr);
String name = user.getString("name");
int age = user.getIntValue("age");
return new User(name, age);
}
@PostMapping("user9")
public User user9(HttpServletRequest request){
String jsonStr = getBody(request);
JSONObject user = JSONObject.parseObject(jsonStr);
String name = user.getString("name");
int age = user.getIntValue("age");
return new User(name, age);
}
@PutMapping("user10")
public User user10(HttpServletRequest request){
String jsonStr = getBody(request);
JSONObject user = JSONObject.parseObject(jsonStr);
String name = user.getString("name");
int age = user.getIntValue("age");
return new User(name, age);
}
@DeleteMapping("user11/{id}")
public String user11(@PathVariable("id") int id){
System.out.println(id);
return "success";
}
@GetMapping("user12")
public User[] user12(String jsonStr){
JSONObject user = JSONObject.parseObject(jsonStr);
String name = user.getString("name");
int age = user.getIntValue("age");
User[] users = {new User(name,age),new User(name, age)};
return users;
}
@GetMapping("user13")
public List<User> user13(String jsonStr){
JSONObject user = JSONObject.parseObject(jsonStr);
String name = user.getString("name");
int age = user.getIntValue("age");
List<User> users = new ArrayList<User>();
users.add(new User(name,age));
users.add(new User(name,age));
return users;
}
private String getBody(HttpServletRequest request){
BufferedReader br = null;
StringBuilder sb = new StringBuilder("");
try
{
br = request.getReader();
String str;
while ((str = br.readLine()) != null)
{
sb.append(str);
}
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (null != br)
{
try
{
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return sb.toString();
}
}
注意:消费者和服务提供者都需要创建User实体。
package com.wya.springboot.controller;
public class User implements Serializable{
private static final long serialVersionUID = -3653242135661883164L;
private String name;
private Integer age;
public User() {
}
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "name=" + name + ", age=" +age;
}
}