1:getForObject
getForObject函数实际上是对getForEntity函数的进一步封装,如果你只关注返回的消息体的内容,对其他信息都不关注,此时可以使用getForObject
@RequestMapping("/book2")
public Book book2() {
Book book = restTemplate.getForObject("http://HELLO-SERVICE/getbook1", Book.class);
return book;
}
不带参数
@GetMapping("/findAll")
public List findAll(){
List list = restTemplate.getForObject(serviceUrl+"userinfo/findAll", List.class);
return list;
}
@GetMapping("/findById")
public Userinfo findById(int uid){
return restTemplate.getForObject(serviceUrl+"userinfo/findById?uid="+uid, Userinfo.class);
}
带参数
@GetMapping("/find1")
public Userinfo find1(int uid){
return restTemplate.getForObject(serviceUrl+"userinfo/findById?uid={1}", Userinfo.class,uid);
}
2:postForObject
如果你只关注,返回的消息体,可以直接使用postForObject。用法和getForObject一致。
@PostMapping("/save")
public ResultVO addOrder2(){
Product product = new Product();
product.setPname("zsf");
product.setPrice(12.0f);
product.setDescribute("hello");
log.info("获取商品{}",product);
ResultVO resultVO = restTemplate.postForObject("http://localhost:8080/product/save",product, ResultVO.class);
log.info("增加结果{}", resultVO);
return resultVO;
}
另外一种姿势的消费者
@PostMapping("/save")
public ResultVO addOrder2(@RequestBody Product product){
log.info("获取商品{}",product);
ResultVO resultVO = restTemplate.postForObject("http://localhost:8080/product/save",product, ResultVO.class);
log.info("增加结果{}", resultVO);
return resultVO;
}
但是发送的数据必须是JSON格式
服务器端处理,必须使用json的数据格式
@PostMapping("/save")
public ResultVO save(@RequestBody Product product) throws JsonProcessingException {
log.info("增加商品:{}",product);
ResultVO<Product> vo = null;
vo = new ResultVO<>(Constants.OPEN_SUCCESS, "增加商品成功", product);
return vo;
}
3:getForEntity
getForEntity方法的返回值是一个ResponseEntity<T>,
ResponseEntity<T>是Spring对HTTP请求响应的封装,
包括了几个重要的元素,如响应码、contentType、contentLength、响应消息体等。
可以用一个数字做占位符,最后是一个可变长度的参数,来一一替换前面的占位符
@GetMapping("/findAll")
public List findAll(){
ResponseEntity<List> responseEntity =
restTemplate.getForEntity(serviceUrl+"userinfo/findAll", List.class);
System.out.println(responseEntity.getStatusCode());
//200 OK
System.out.println(responseEntity.getHeaders());
//[Content-Type:"application/json", Transfer-Encoding:"chunked",
// Date:"Thu, 04 Jun 2020 06:39:59 GMT", Keep-Alive:"timeout=60",
//Connection:"keep-alive"]
System.out.println(responseEntity.getBody());//json
return responseEntity.getBody();
}
可以前面使用name={name}这种形式,最后一个参数是一个map,map的key即为前边占位符的名字,map的value为参数值
@RequestMapping("/sayhello2")
public String sayHello2() {
Map<String, String> map = new HashMap<>();
map.put("name", "李四");
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/sayhello?name={name}", String.class, map);
return responseEntity.getBody();
}
@GetMapping("/{pid}")
public ResultVO addOrder3(@PathVariable Integer pid){
ResponseEntity<ResultVO> responseEntity = restTemplate.getForEntity("http://localhost:8080/product/{pid}", ResultVO.class,pid);
log.info("消费结果{}", responseEntity.getBody());
log.info("消费结果{}", responseEntity);
return responseEntity.getBody();
}
4:postForEntity
方法的第一参数表示要调用的服务的地址 第二个参数表示上传的参数 第三个参数表示返回的消息体的数据类型
@RequestMapping("/book3")
public Book book3() {
Book book = new Book();
book.setName("李四");
ResponseEntity<Book> responseEntity = restTemplate.postForEntity("http://HELLO-SERVICE/getbook2", book, Book.class);
return responseEntity.getBody();
}
服务端
@RequestMapping(value = "/getbook2", method = RequestMethod.POST)
public Book book2(@RequestBody Book book) {
System.out.println(book.getName());
book.setPrice(33);
book.setAuthor("李四");
book.setPublisher("吃了吗");
return book;
}
@PostMapping("/save1")
public ResultVO addOrder21(Product product){
log.info("获取商品{}",product);
ResponseEntity<ResultVO> responseEntity = restTemplate.postForEntity("http://localhost:8080/product/save",product, ResultVO.class);
log.info("增加结果{}", responseEntity);
return responseEntity.getBody();
}
5:exchange
exchange方法提供统一的方法模板进行四种请求:POST,PUT,DELETE,GET
GET请求
ResponseEntity<String> results = restTemplate.exchange(url,HttpMethod.GET, null, String.class, params);
说明:1)url: 请求地址;
2)method: 请求类型(如:POST,PUT,DELETE,GET);
3)requestEntity: 请求实体,封装请求头,请求内容
4)responseType: 响应类型,根据服务接口的返回类型决定
5)uriVariables: url中参数变量值
@GetMapping("/save/{pid}")
public ResultVO addOrder4(@PathVariable Integer pid){
ResponseEntity<ResultVO> results = restTemplate.exchange(url+"product/"+pid, HttpMethod.GET, null, ResultVO.class);
log.info("增加结果{}", results);
return results.getBody();
}
DELETE请求
提供者
@DeleteMapping("/{pid}")
public ResultVO save(@PathVariable Integer pid) throws JsonProcessingException {
log.info("删除商品:{}",pid);
boolean success = productService.removeById(pid);
ResultVO vo = new ResultVO<>(Constants.OPEN_SUCCESS, "删除商品", success);
return vo;
}
消费者
@DeleteMapping("/{pid}")
public ResultVO deleteOrder(@PathVariable Integer pid){
ResponseEntity<ResultVO> results = restTemplate.exchange(url+"product/"+pid, HttpMethod.DELETE, null, ResultVO.class);
log.info("增加结果{}", results);
return results.getBody();
}
POST请求
提供者
@PostMapping("/save")
public ResultVO save(@RequestBody Product product) throws JsonProcessingException {
log.info("增加商品:{}",product);
ResultVO<Product> vo = null;
if(productService.save(product))
vo = new ResultVO<>(Constants.OPEN_SUCCESS, "增加商品成功", product);
else
vo = new ResultVO<>(Constants.OPEN_FAILURE, "增加商品失败", product);
return vo;
}
消费者
@PostMapping("/saveP")
public ResultVO addOrder31(@RequestBody Product product) throws JsonProcessingException {
log.info("获取商品{}",product);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String json = new ObjectMapper().writeValueAsString(product);
HttpEntity<String> entity = new HttpEntity<String>(json,headers);
ResponseEntity<ResultVO> resp = restTemplate.exchange("http://localhost:8080/product/save", HttpMethod.POST,entity, ResultVO.class,product);
log.info("增加结果{}", resp);
return resp.getBody();
}
PUT请求
提供者
@PutMapping("/update")
public ResultVO update(@RequestBody Product product) throws JsonProcessingException {
log.info("修改商品:{}",product);
ResultVO<Product> vo = null;
if(productService.updateById(product))
vo = new ResultVO<>(Constants.OPEN_SUCCESS, "增加修改成功", product);
else
vo = new ResultVO<>(Constants.OPEN_FAILURE, "增加修改失败", product);
return vo;
}
消费者
@PutMapping("/update")
public ResultVO update(@RequestBody Product product) throws JsonProcessingException {
log.info("获取商品{}",product);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String json = new ObjectMapper().writeValueAsString(product);
log.info(json);
HttpEntity<String> entity = new HttpEntity<String>(json,headers);
ResponseEntity<ResultVO> resp = restTemplate.exchange("http://localhost:8080/product/update", HttpMethod.PUT,entity, ResultVO.class,product);
log.info("修改结果{}", resp);
return resp.getBody();
}
携带head和cookie
提供者
@PutMapping("/withCookie")
public String withCookie(@RequestBody Product product,HttpServletRequest request) throws JsonProcessingException {
log.info("提供者获取到{}", product.getPname());
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()){
String s = headerNames.nextElement();
System.out.println(s+" "+request.getHeader(s));
}
Cookie[] cookies = request.getCookies();
if(cookies!=null)
for (Cookie cookie : cookies) {
log.info(cookie.getName() + "=" + cookie.getValue());
}
return "success";
}
消费者
@PutMapping("/withCookie")
public String withCookie() throws JsonProcessingException {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
List<String> cookies = new ArrayList();
cookies.add("uname=zsf");
requestHeaders.put("Cookie", cookies);//将cookie放在header中发送
requestHeaders.add("Authorization", "123456");
Product product = new Product();
product.setPname("价格贵的不得了");
product.setPrice(12.0F);
String json = new ObjectMapper().writeValueAsString(product);
HttpEntity<String> entity = new HttpEntity<String>(json, requestHeaders);
ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/product/withCookie",
HttpMethod.PUT,entity, String.class,product);
return resp.getBody();
}