Spring Cloud系列(七) RestTemplate详解(Finchley.RC2版本)

GET请求

在RestTemplate中对GET请求可以通过如下两种方式实现。

第一种,getForEntity方法。该方法返回的是ResponseEntity,该对象是Spring对Http请求响应的封装。其中主要存储了HTTP的几个重要元素,比如HTTP请求状态码的枚举对象HttpStatus(我们常说的404,500)、在他的父类HttpEntity中还存储着HTTP请求的头信息对象HttpHeaders以及泛型类型的请求体对象(响应码、contentType、contentLength、响应消息体等)。

返回字符串类型的对象

ResponseEntity responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/ribbon/user1?name={1}", String.class,"rest1");
String body = responseEntity.getBody();

返回自定义类的对象

//返回对象格式
ResponseEntity responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/ribbon/user2?name={1}&age={2}", User.class,"rest2",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 responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/ribbon/user3?jsonStr={jsonStr}", User.class,"{\"name\":\"rest3\",\"age\":\"22\"}");
User user = responseEntity.getBody();

2.getForEntity(String url,Class responseType,Map urlVariables)

这里urlVariables参数类型是Map,所以在使用该方法进行参数绑定时必须在占位符中指定Map中参数的key值。

Map params = new HashMap();
params.put("name", "rest4");
params.put("age", 22);
ResponseEntity responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/ribbon/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/ribbon/user1?name={name}").build().expand("rest5").encode();
URI uri = uriComponents.toUri();
ResponseEntity responseEntity = restTemplate.getForEntity(uri, String.class);

第二种,getForObject方法。该方法可以理解为getForEntity方法的进一步封装。它通过HttpMessageConverterExtractor对HTTP的请求响应体body内容进行对象转换,实现请求直接返回包装好的对象内容,该函数少了一步获取body的步骤所以更方便。比如:

String result = restTemplate.getForObject("http://HELLO-SERVICE/ribbon/user1?name={1}",String.class,"rest6");
//返回对象格式
User user = restTemplate.getForObject("http://HELLO-SERVICE/ribbon/user2?name={1}&age={2}", User.class, "rest7",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为请求响应的body类型。比如:

// 参数
User user = new User(1, "rest8", 23);
ResponseEntity responseEntity = restTemplate.postForEntity("http://HELLO-SERVICE/ribbon/user4", user,User.class);

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 map= new LinkedMultiValueMap();
map.add("age", "33");
HttpEntity> request = new HttpEntity>(map, headers);
ResponseEntity responseEntity = restTemplate.postForEntity("http://HELLO-SERVICE/ribbon/user5", request, User.class);

第二种,postForObject方法。该方法和getForObject方法类似,它的作用是简化postForEntity的后续处理,通过直接将请求响应的body内容包装成对象来使用。

User user = restTemplate.postForObject("http://HELLO-SERVICE/ribbon/user4", new User(1,"rest10", 22), User.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。

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("rest11",22);
restTemplate.put("http://HELLO-SERVICE/ribbon/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/ribbon/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()函数

当然也可以用统一的模板进行GET、POST、PUT、DELETE这四种方式的请求。

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 entity = new HttpEntity(params,headers);
ResponseEntity resp = restTemplate.exchange("http://HELLO-SERVICE/ribbon/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 entity = new HttpEntity(params,headers);
ResponseEntity resp = restTemplate.exchange("http://HELLO-SERVICE/ribbon/user10", HttpMethod.PUT, entity, String.class);

DELETE请求


ResponseEntity resp = restTemplate.exchange("http://HELLO-SERVICE/ribbon/user11/{1}", HttpMethod.DELETE, null, String.class,1);

GET请求

ResponseEntity resp = restTemplate.exchange("http://HELLO-SERVICE/ribbon/user8?jsonStr={jsonStr}",
				HttpMethod.GET, null, User.class, "{\"id\":\"2\",\"name\":\"rest13\",\"age\":33}");

如果返回复杂的数据比如数组或list需要用下面的方式

StringBuilder sb = new StringBuilder();
ResponseEntity resp = restTemplate.exchange("http://HELLO-SERVICE/user12?jsonStr={jsonStr}", HttpMethod.GET, null, User[].class,"{\"name\":\"rest17\",\"age\":33}");
for(User user : resp.getBody()){
	sb.append(user.toString()+"
"); }
StringBuilder sb = new StringBuilder();
ParameterizedTypeReference> res = new ParameterizedTypeReference>(){};
ResponseEntity> resp = restTemplate.exchange("http://HELLO-SERVICE/user13?jsonStr={jsonStr}", HttpMethod.GET, null, res,"{\"name\":\"rest18\",\"age\":33}");
for(User user : resp.getBody()){
	sb.append(user.toString()+"
"); }

对于返回属性中有范型数据的复合对象,比如分页对象

ResponseEntity 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 page = mapper.readValue(results.getBody(), new TypeReference>() { });

最后附上代码

消费者代码

import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
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;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

@RestController
public class RestTemplateController {

	@Autowired
	private RestTemplate restTemplate;

	/**
	 * getForEntity-返回字符串对象
	 * 
	 * @return
	 */
	@GetMapping("rest1")
	public String rest1() {
		ResponseEntity responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/ribbon/user1?name={1}",
				String.class, "rest1");
		String body = responseEntity.getBody();
		return body;
	}

	/**
	 * getForEntity-返回User对象
	 * 
	 * @return
	 */
	@GetMapping("rest2")
	public String rest2() {
		ResponseEntity responseEntity = restTemplate
				.getForEntity("http://HELLO-SERVICE/ribbon/user2?name={1}&age={2}", User.class, "rest2", 22);
		User user = responseEntity.getBody();
		return user.toString();
	}

	/**
	 * getForEntity-以json字符串当作参数
	 * 
	 * @return
	 */
	@GetMapping("rest3")
	public String rest3() {
		ResponseEntity responseEntity = restTemplate.getForEntity(
				"http://HELLO-SERVICE/ribbon/user3?jsonStr={jsonStr}", User.class, "{\"name\":\"rest3\",\"age\":22}");
		User user = responseEntity.getBody();
		return user.toString();
	}

	/**
	 * getForEntity-以Map当作参数
	 * 
	 * @return
	 */
	@GetMapping("rest4")
	public String rest4() {
		Map params = new HashMap();
		params.put("name", "rest4");
		params.put("age", 22);
		ResponseEntity responseEntity = restTemplate
				.getForEntity("http://HELLO-SERVICE/ribbon/user2?name={name}&age={age}", User.class, params);
		User user = responseEntity.getBody();
		return user.toString();
	}

	/**
	 * getForEntity-URI代替url+urlVariables
	 * 
	 * @return
	 */
	@GetMapping("rest5")
	public String rest5() {
		UriComponents uriComponents = UriComponentsBuilder
				.fromUriString("http://HELLO-SERVICE/ribbon/user1?name={name}").build().expand("rest5").encode();
		URI uri = uriComponents.toUri();
		ResponseEntity responseEntity = restTemplate.getForEntity(uri, String.class);
		return responseEntity.getBody();
	}

	/**
	 * getForObject 返回字符串
	 * 
	 * @return
	 */
	@GetMapping("rest6")
	public String rest6() {
		String result = restTemplate.getForObject("http://HELLO-SERVICE/ribbon/user1?name={1}", String.class, "rest6");
		return result;
	}

	/**
	 * getForObject 返回User对象
	 * 
	 * @return
	 */
	@GetMapping("rest7")
	public String rest7() {
		User user = restTemplate.getForObject("http://HELLO-SERVICE/ribbon/user2?name={1}&age={2}", User.class, "rest7",
				22);
		return user.toString();
	}

	/**
	 * postForEntity
	 * 
	 * @return
	 */
	@GetMapping("rest8")
	public String rest8() {
		// 参数
		User user = new User(1, "rest8", 23);
		ResponseEntity responseEntity = restTemplate.postForEntity("http://HELLO-SERVICE/ribbon/user4", user,
				User.class);
		return responseEntity.getBody().toString();
	}

	/**
	 * postForEntity,HttpEntity传参
	 * 
	 * @return
	 */
	@GetMapping("rest9")
	public String rest9() {
		HttpHeaders headers = new HttpHeaders();
		headers.add("token", "xxxxxxxxxxx");
		HttpEntity httpEntity = new HttpEntity(headers);
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		MultiValueMap map = new LinkedMultiValueMap();
		map.add("age", "33");
		HttpEntity> request = new HttpEntity>(map, headers);
		ResponseEntity responseEntity = restTemplate.postForEntity("http://HELLO-SERVICE/ribbon/user5", request,
				User.class);
		return responseEntity.getBody().toString();
	}

	/**
	 * postForObject
	 * 
	 * @return
	 */
	@GetMapping("rest10")
	public String rest10() {
		User user = restTemplate.postForObject("http://HELLO-SERVICE/ribbon/user4", new User(1, "rest10", 22),
				User.class);
		return user.toString();
	}

	/**
	 * put请求
	 * 
	 * @return
	 */
	@GetMapping("rest11")
	public String rest11() {
		int id = 1;
		User user = new User("rest11", 22);
		restTemplate.put("http://HELLO-SERVICE/ribbon/user6/{1}", user, id);
		return "success";
	}

	/**
	 * delete请求
	 * 
	 * @return
	 */
	@GetMapping("rest12")
	public String rest12() {
		int id = 1;
		restTemplate.delete("http://HELLO-SERVICE/ribbon/user7/{1}", id);
		return "success";
	}

	/**
	 * exchange实现的GET请求
	 * 
	 * @return
	 */
	@GetMapping("rest13")
	public String rest13() {
		ResponseEntity resp = restTemplate.exchange("http://HELLO-SERVICE/ribbon/user8?jsonStr={jsonStr}",
				HttpMethod.GET, null, User.class, "{\"id\":\"2\",\"name\":\"rest13\",\"age\":33}");
		return resp.getBody().toString();
	}

	/**
	 * exchange实现的POST请求
	 * 
	 * @return
	 */
	@GetMapping("rest14")
	public String rest14() {
		String params = "{\"name\":\"小明\",\"age\":33}";
		HttpHeaders headers = new HttpHeaders();
		// 解决参数乱码的问题
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);
		HttpEntity entity = new HttpEntity(params, headers);
		ResponseEntity resp = restTemplate.exchange("http://HELLO-SERVICE/ribbon/user9", HttpMethod.POST, entity,
				User.class);
		return resp.getBody().toString();
	}

	/**
	 * exchange实现的PUT请求
	 * 
	 * @return
	 */
	@GetMapping("rest15")
	public String rest15() {
		String params = "{\"name\":\"小明\",\"age\":33}";
		HttpHeaders headers = new HttpHeaders();
		// 解决参数乱码的问题
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);
		HttpEntity entity = new HttpEntity(params, headers);
		ResponseEntity resp = restTemplate.exchange("http://HELLO-SERVICE/ribbon/user10", HttpMethod.PUT,
				entity, String.class);
		return resp.getBody();
	}

	/**
	 * exchange实现的DELETE请求
	 * 
	 * @return
	 */
	@GetMapping("rest16")
	public String rest16() {
		ResponseEntity resp = restTemplate.exchange("http://HELLO-SERVICE/ribbon/user11/{1}", HttpMethod.DELETE,
				null, String.class, 1);
		return resp.getBody();
	}

	/**
	 * 返回格式是对象数组
	 * 
	 * @return
	 */
	@GetMapping("rest17")
	public String rest17() {
		StringBuilder sb = new StringBuilder();
		ResponseEntity resp = restTemplate.exchange("http://HELLO-SERVICE/ribbon/user12?jsonStr={jsonStr}",
				HttpMethod.GET, null, User[].class, "{\"name\":\"rest17\",\"age\":33}");
		for (User user : resp.getBody()) {
			sb.append(user.toString() + "
"); } return sb.toString(); } /** * 返回格式是List集合 * * @return */ @GetMapping("rest18") public String rest18() { StringBuilder sb = new StringBuilder(); ParameterizedTypeReference> res = new ParameterizedTypeReference>() { }; ResponseEntity> resp = restTemplate.exchange("http://HELLO-SERVICE/ribbon/user13?jsonStr={jsonStr}", HttpMethod.GET, null, res, "{\"name\":\"rest18\",\"age\":33}"); for (User user : resp.getBody()) { sb.append(user.toString() + "
"); } return sb.toString(); } }

服务提供者代码

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.wya.springboot.controller.User;

@RestController
@RequestMapping("ribbon")
public class UserController {

	@GetMapping("user1")
	public String user1(String name) {
		return name;
	}

	@GetMapping("user2")
	public User user2(String name, int age) {
		return new User(1, name, age);
	}

	@GetMapping("user3")
	public User user3(String jsonStr) {
		JSONObject userJson = JSONObject.parseObject(jsonStr);
		return new User(1, userJson.getString("name"), userJson.getIntValue("age"));
	}

	@PostMapping("user4")
	public User user4(@RequestBody User user) {
		return user;
	}

	@PostMapping("user5")
	public User user5(int age, HttpServletRequest request) {
		String token = request.getHeader("token");
		return new User(1, token, age);
	}

	@PutMapping("user6/{id}")
	public User user6(@PathVariable("id") int id, @RequestBody User user) {
		user.setId(id);
		return user;
	}

	@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);
		int id = user.getIntValue("id");
		String name = user.getString("name");
		int age = user.getIntValue("age");
		return new User(id, 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(1, 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(1, 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(1,name, age), new User(2,name, age) };
		return users;
	}

	@GetMapping("user13")
	public List user13(String jsonStr) {
		JSONObject user = JSONObject.parseObject(jsonStr);
		String name = user.getString("name");
		int age = user.getIntValue("age");
		List users = new ArrayList();
		users.add(new User(1,name, age));
		users.add(new User(2,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实体。

public class User implements Serializable{
	private static final long serialVersionUID = -3653242135661883164L;
	private Integer id;
	private String name;
    private Integer age;

    public User() {
    }
    
    public User(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}

    public User(Integer id, String name, Integer age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}



	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	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 "User [id=" + id + ", name=" + name + ", age=" + age + "]";
	}


}

 

你可能感兴趣的:(Spring,Cloud)