SpringBoot(6)---RestTemplate⽅法详解(2)SpringBoot (6)---RestTemplate⽅法详解(2)
说明
上⼀篇简单运⽤了RestTemplate,
本篇主要讲解RestTemplate的主要请求⽅法, getForObject, getForEntity, exchange(⽅法列举只⽤了Get)。Method包括GET、POST、PUT、DELETE。参数传递,解析等。
在讲述使⽤之前,想要理解SpringMVC的⼏个常⽤注解:
1. @Controller:修饰class,⽤来创建处理http请求的对象
2. @RestController:Spring4之后加⼊的注解,原来在@Controller中返回json需要@ResponseBody来配合,如果直接
⽤@RestController替代@Controller就不需要再配置@ResponseBody,默认返回json格式。
3. @RequestMapping:配置url映射
4. @PostMapping: 这个是@RequestMapping+POST⽅法的简写
5. @RequestHeader: 请求Header参数
6. @PathVariable: URL路径参数,⽐如/user/{id}中的id参数
7. @RequestParam: URL请求参数,⽐如/user?id=1中的id参数
8. @RequestBody: 请求Body参数
⼯程建⽴
参照教程新建⼀个Spring Boot项⽬,名字叫demoresttemplatemethod, 在⽬录src/main/java/resources 下到配置⽂
件application.properties,重命名为l。
创建RestTemplateConfig配置类
请求都需要⽤到restTemplate对象,⽤@Bean的⽅式注⼊,⽤同⼀个⼯⼚对象统⼀管理ClientHttpRequestFactory。
新建类:
figure;
import t.annotation.Bean;
import t.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setReadTimeout(5000);//ms
factory.setConnectTimeout(15000);//ms
return factory;
}
}
创建Model对象User
结果实体User⽤于数据传递,新建类
del;
public class User {
private Integer id;
private String methodName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", methodName='" + methodName + '\'' +
'}';
}
}
创建Restful被调⽤类
REST,即Representational State Transfer的缩写,对这个词组的翻译是表现层状态转化。
RESTful是⼀种软件设计风格,就是⽬前最流⾏的⼀种互联⽹软件架构。它结构清晰、符合标准、易于理解、扩展⽅便,所以正得到越来越多⽹站的采⽤。
这⾥为了演⽰,会将数据保存到内存Map中,实际使⽤肯定是保存到数据库中。
创建Restful被调⽤类:
调⽤⽅法包括GET、POST、PUT、DELETE, 以及带参数的例⼦。
说明:PUT是幂等性⽅法,也就是请求多次跟⼀次的效果⼀样,就像转账⼀样,⼀次转账弱⽹情况下可能会重试,但是结果不会因为多次尝试⽽不⼀样, ⼀般⽤户更新。⽽POST不是幂等性的⽅法,也就是多次重试,会有多个结果,⼀般⽤于创建。
peace.demoresttemplatemethod.web;
del.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@RequestMapping(value = "/testGet", method = RequestMethod.GET)
public User testGet() {
User user = new User();
user.setId(1);
user.setMethodName("get");
return user;
}
@RequestMapping(value = "/testPost", method = RequestMethod.POST)
public User testPost() {
User user = new User();
user.setId(1);
user.setMethodName("post");
return user;
}
@RequestMapping(value = "/testPostParam", method = RequestMethod.POST)
public String testPostParam(@RequestParam("id") String id, @RequestParam("methodName") String methodName) { System.out.println("Post id: " + id);
System.out.println("Post methodName: " + methodName);
return "post id{" + id + "} success";
}
@RequestMapping(value = "/testPut", method = RequestMethod.PUT)
public String testPut(@RequestParam("id") String id, @RequestParam("methodName") String methodName) {
System.out.println("put id: " + id);
System.out.println("put methodName: " + methodName);
return "put id{" + id + "} success";
}
@RequestMapping(value = "/testDel", method = RequestMethod.DELETE)
public String testDel(@RequestParam("id") String id) {
System.out.println("del id: " + id);
return "del id{" + id + "} success";
}
}
RequestParam解析:
例⼦:@RequestParam(value = "name", required = true, defaultValue = "defaultName"
@RequestParam ⽀持下⾯四种参数
name 绑定本次参数的名称,要跟URL上⾯的⼀样
value 跟name⼀样的作⽤,是name属性的⼀个别名
springboot结构defaultValue 如果本次请求没有携带这个参数,或者参数为空,那么就会启⽤默认值
required 这个参数是不是必须的
创建使⽤RestTemplate调⽤Rest接⼝的Controller
调⽤的⽅法包括:getForObject, getForEntity, exchange(⽅法列举只⽤了Get,Method包括GET、POST、PUT、DELETE).新建类peace.demoresttemplatemethod.web.UserRequestController
peace.demoresttemplatemethod.web;
del.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
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 java.URI;
import java.URISyntaxException;
@RestController
public class UserRequestController {
@Autowired
private RestTemplate restTemplate;
private static String PROTOCOL = "http";
private static String HOST = "localhost";
private static String PORT = "8080";
private static String PRE_URL = PROTOCOL + "://" + HOST + ":" + PORT + "/";
private static String GET_URL = PRE_URL + "testGet";
private static String POST_URL = PRE_URL + "testPost";
private static String POST_PARAM_URL = PRE_URL + "testPostParam";
private static String PUT_URL = PRE_URL + "testPut";
private static String DEL_URL = PRE_URL + "testDel";
@GetMapping("/requestTestGet")
public String requestTestGet() throws URISyntaxException {
/
/ 1. getForObject()
User user1 = ForObject(GET_URL, User.class);
System.out.println("get user1: " + user1);
// 2. getForEntity()
ResponseEntity<User> responseEntity1 = ForEntity(GET_URL, User.class);
HttpStatus statusCode = StatusCode();
HttpHeaders header = Headers();
User user2 = Body();
System.out.println("get user2: " + user2);
System.out.println("get statusCode: " + statusCode);
System.out.println("get header: " + header);
/
/ 3. exchange()
RequestEntity requestEntity = (new URI(GET_URL)).build();
ResponseEntity<User> responseEntity2 = hange(requestEntity, User.class);
User user3 = Body();
System.out.println("get user3: " + user3);
return "requestTestGet";
}
@GetMapping("/requestTestPost")
public String requestTestPost() throws URISyntaxException {
HttpHeaders headers = new HttpHeaders();
String data = new String();
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论