An overview of
The previous article described how to use Spring Boot to build RESTful Web services, juejin.cn/post/695494… After the Web service construction is completed, in most cases, the interface will be provided to the front-end partner to call, and the actual development process will also involve the back-end to call another back-end written interface, what we need to do is how to consume the service, there are three ways commonly used at present
- JDK built-in HttpConnection
- The Apache HttpClient
- Spring encapsulates the RestTemplate
RestTemplate does not implement the Http stack itself. Spring defines a template, like JDBCTemplate, that actually sends Http requests through HttpConnetion or HttpClient. You can specify which library to use when you customize the RestTemplate. Of course, RestTemplate offers many improvements over the traditional HttpClient client utility library in terms of ease of coding and exception handling.
This section describes common methods of RestTemplate
On remote access, RestTemplate comes with a set of common utility methods that can be grouped according to HTTP semantics and RESTful design principles:
HTTP method | RestTemplate method group |
---|---|
GET | getForObject/getForEntity |
POST | postForLocation/postForObject/postForEntity |
PUT | put |
DELETE | delete |
Header | headForHeaders |
There is no limit | Exchange/execute |
Ok, now that we’ve covered the common methods, let’s go through a simple introduction that takes those methods aside. Note that this introductory Demo relies on the previous section on building the interface services provided by RESTful Web services
Simple introduction
The repository address corresponding to the instance code:
Github.com/dragon8844/…
Gitee.com/drag0n/spri…
Introduction of depend on
Introduce dependencies into the pom.xml file:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<! -- Simplify code -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<! Httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<! Write unit tests later -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
Copy the code
Add the configuration
Create the application configuration file application.yml in the resources directory. We use port 8081,8080 for RESTful web services and add the following configuration:
Port used to modify the Web service
server:
port: 8081
Copy the code
Write the code
Custom RestTemplate
@Bean
public RestTemplate customRestTemplate(a){
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpRequestFactory.setConnectionRequestTimeout(3000);
httpRequestFactory.setConnectTimeout(3000);
httpRequestFactory.setReadTimeout(3000);
return new RestTemplate(httpRequestFactory);
}
Copy the code
Define the unified response VO R
@Data
public class R<T> implements Serializable {
private static final String DEFAULT_SUCCESS_MSG = "Request successful";
private static final int DEFAULT_SUCCESS_CODE = 0;
public static final int SUCCESS = DEFAULT_SUCCESS_CODE;
private Integer code;
private String msg;
private T data;
public static<T> R ok(T data){
R jsonResult = new R();
jsonResult.setCode(DEFAULT_SUCCESS_CODE);
jsonResult.setMsg(DEFAULT_SUCCESS_MSG);
jsonResult.setData(data);
return jsonResult;
}
public static<T> R err(int code, String msg , T data){
R jsonResult = new R();
jsonResult.setCode(code);
jsonResult.setMsg(msg);
jsonResult.setData(data);
return jsonResult;
}
public static<T> R err(int code, String msg){
R jsonResult = new R();
jsonResult.setCode(code);
jsonResult.setMsg(msg);
returnjsonResult; }}Copy the code
Define User request VO
@Data
public class UserReqVO implements Serializable {
private String username;
private String password;
}
Copy the code
Define User to respond to VO
@Data
public class UserRespVO implements Serializable {
private Integer id;
private String username;
private Date createTime;
}
Copy the code
Write UserClient to access the interface using restTemplate
@Component
@Slf4j
public class UserClient {
@Resource
RestTemplate restTemplate;
public R<UserRespVO> getForObject(Integer id){
Map<String, Object> uriVariables = new HashMap<>(1);
uriVariables.put("id", id);
R r = restTemplate.getForObject("http://localhost:8080/v1/user/{id}", R.class, uriVariables);
return r;
}
public R<UserRespVO> getForEntity(Integer id){
Map<String, Object> uriVariables = new HashMap<>(1);
uriVariables.put("id", id);
ResponseEntity<R> r = restTemplate.getForEntity("http://localhost:8080/v1/user/{id}", R.class,uriVariables);
log.info(r.getHeaders().toString());
return r.getBody();
}
public R<Boolean> postForObject(UserReqVO userReqVO){
R r = restTemplate.postForObject("http://localhost:8080/v1/user", userReqVO, R.class);
return r;
}
public R<Boolean> postForEntity(UserReqVO userReqVO){
ResponseEntity<R> r = restTemplate.postForEntity("http://localhost:8080/v1/user", userReqVO, R.class);
log.info(r.getHeaders().toString());
return r.getBody();
}
/** * Exchange is a common and uniform method for sending GET and POST requests as well as various other types of requests. *@return* /
public R<UserRespVO> exchange(Integer id){
Map<String, Object> uriVariables = new HashMap<>(1);
uriVariables.put("id", id);
ResponseEntity<R> r = restTemplate.exchange("http://localhost:8080/v1/user/{id}", HttpMethod.GET, null, R.class, uriVariables);
log.info(r.getHeaders().toString());
return r.getBody();
}
public R<Boolean> put(Integer id, UserReqVO userReqVO){
restTemplate.put("http://localhost:8080/v1/user/{id}", userReqVO, id);
return R.ok(true);
}
public R<Boolean> delete(Integer id){
restTemplate.delete("http://localhost:8080/v1/user/{id}", id);
return R.ok(true); }}Copy the code
-
GetForObject () sends an HTTP GET request, and the returned request body is mapped to a business object
-
GetForEntity () sends an HTTP GET request, returns a ResponseEntity containing the business object mapped to the response body, which also contains HTTP messages and other information, and the getForObject method returns only the business object
-
PostForObject () posts data to a URL that returns an object based on the response body match
-
PostForEntity () posts data to a URL and returns a ResponseEntity that contains an object that is mapped from the response body. Like getForEntity, the ResponseEntity object also contains HTTP messages and other information.
-
Put () Puts a resource to a specific URL
-
Delete () performs HTTP delete on a resource at a specific URL
-
Exchange (), which performs specific HTTP methods on urls, is a common and uniform method that can be used to send GET and POST requests as well as various other types of requests. Return the ResponseEntity containing the object mapped from the response body and containing HTTP message and other information.
Unit testing
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class UserClientTest {
@Resource
UserClient userClient;
@Test
public void getForObject(a) {
R r = userClient.getForObject(9991);
log.info("result : {}", r);
}
@Test
public void getForEntity(a) {
R r = userClient.getForEntity(9991);
log.info("The result: {}", r);
}
@Test
public void postForObject(a) {
UserReqVO userReqVO = new UserReqVO();
userReqVO.setUsername("Zhang");
userReqVO.setPassword("123456");
R r = userClient.postForObject(userReqVO);
log.info("result : {}", r);
}
@Test
public void postForEntity(a) {
UserReqVO userReqVO = new UserReqVO();
userReqVO.setUsername("Zhang");
userReqVO.setPassword("123456");
R r = userClient.postForEntity(userReqVO);
log.info("result : {}", r);
}
@Test
public void exchange(a) {
R r = userClient.exchange(9991);
log.info("result : {}", r);
}
@Test
public void put(a) {
UserReqVO userReqVO = new UserReqVO();
userReqVO.setUsername("Zhang");
userReqVO.setPassword("123456");
R r = userClient.put(1,userReqVO);
log.info("result : {}", r);
}
@Test
public void delete(a) {
R r = userClient.delete(1);
log.info("result : {}",r); }}Copy the code
summary
We built the foundation of RESTful Web services in Spring Boot and implemented access to remote service interfaces by introducing the RestTemplate template, which provides developers with a large number of useful tool methods to realize the sending of HTTP requests and the retrieval of responses. At the same time, the template class also developed some custom entry for developers to embed, used to implement the FINE management of THE HTTP request process processing logic. RestTemplate, like JdbcTemplate, is a very effective utility class in terms of design and implementation. Hope you found this simple introduction helpful
One last word
If this article is helpful to you, or inspired, help pay attention to it, your support is the biggest motivation I insist on writing, thank you for your support.
In addition, pay attention to the public number: black lighthouse, focus on Java back-end technology sharing, covering Spring, Spring the Boot, SpringCloud, Docker, Kubernetes middleware technology, etc.