If there is the concept of flying in the sky, there must be the realization of landing
Ten times of concept is not as good as one time of code. Friend, I hope you can type all the code cases in this article
Praise before you see, form a habit
Spring boot text tutorial series article directory
- Spring boot picture and text tutorial 1 - setting up the spring boot + mybatis environment
- Spring boot graphic tutorial 2 - use of log "logback" and "log4j"
- Spring boot graphic tutorial 3 - "first love complex" integration
- Spring boot picture and text tutorial 4 - spring boot implementation file upload and download
- Spring boot graphic tutorial 5 - using Aop in spring boot
- Spring boot picture and text tutorial 6 - use of filters in spring boot
- Spring boot graphic tutorial 7 - the usage posture of spring boot interceptor
- SpringBoot graphic tutorial 8 - SpringBoot integrated MBG "code generator"
- Spring boot graphic Tutorial 9 - Import and export Excel "Apache Poi" from spring boot
- Spring boot picture and text tutorial 10 - template export | million data Excel export | picture export | easypoi "
- Spring boot graphic tutorial 11 - never write mapper file "SpringBoot integration MybatisPlus"
- Spring boot tutorial 12 - basic use of spring data JPA
- Spring boot graph and text tutorial 13 - hot deployment of code implemented by spring boot + idea
- Spring boot graphic tutorial 14 - Alibaba open source EasyExcel "design for reading and writing millions of data"
- Spring boot graphic tutorial 15 - what about project exceptions? Jump to 404 error page, global exception capture
- Spring boot graphic tutorial 16 - SpringBoot multi module development "web", "package"
Preface
Ask a question: how to send Http request through Java code and request the Controller method of another Java program?
It seems that we really touch the blind area of knowledge
In the previous code, the Java program is the requested party. The request is sent by either Ajax, browser or postman. Today, let's learn how to send Http requests through Java code.
Use of RestTemplate
Preparation work "can be skipped without affecting the tutorial learning"
Because we need to send a request through RestTemplate to request the Controller layer method (Interface) of another project, we need a requested project first.
About this project, I have set up the code cloud address: https://gitee.com/bingqilinpeishenme/boot-demo/tree/master/boot-base-rest
There are three methods in the project: test Get request and Post request as follows
package com.lby.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; /** * @author luxiaoyang * @create 2020-03-18-20:02 */ @Controller public class TestController { /** * @GetMapping("testRestGet") The current method only accepts Get requests * Equivalent to * @RequestMapping(path = "testRestGet",method = RequestMethod.GET) */ @GetMapping("testRestGet") @ResponseBody public String testRestGet(String username){ return "This is a Get Request, accept parameters:"+username; } /** * @PostMapping("") The current method only accepts Post requests * Equivalent to * @RequestMapping(path = "testRestPost",method = RequestMethod.POST) */ @PostMapping("testRestPost") @ResponseBody public String testRestPost(String username){ return "This is a Post Request, accept parameters:"+username; } /** * Test postForLocation to respond to the url address of RestTemplate */ @PostMapping("testRestPostLocation") public String testRestPostLocation(String username){ System.out.println(username); return "redirect:/success.html"; } }
What is RestTemplate
The template class encapsulated in Spring to send RestFul request through Java code, with built-in method to send get post delete and other requests, can be directly used in Spring boot as long as the dependency of importing Spring boot starter web is imported.
Quick start
Determine the dependency of importing spring boot starter web into the project.
Step 1: configure RestTemplate
/** * RestTemplate To configure */ @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory) { return new RestTemplate(factory); } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory() { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); // Timeout settings factory.setReadTimeout(5000);//ms factory.setConnectTimeout(15000);//ms return factory; } }
Step 2: send the request directly using the Api of RestTemplate
In this step, we directly send a Get request in the test class, conduct a simple test, feel the effect, and then conduct more in-depth API learning.
package com.lby; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; @RunWith(SpringRunner.class) @SpringBootTest(classes = {BootResttemplateApplication.class}) public class BootResttemplateApplicationTests { @Autowired private RestTemplate restTemplate; /** * Test get request */ @Test public void test1(){ /** * getForObject * * Required url for address to be requested for parameter 1 * Parameter 2 response data type is String or Map and other required items * Parameter 3 request to carry parameter optional * * getForObject The return value of the method is the response data of the called interface */ String result = restTemplate.getForObject("http://localhost:8802/product/showProductById?id=1", String.class); System.out.println(result); } }
Main API of RestTemplate
HTTP Method | RestTemplate Methods |
---|---|
Get | getForObject, getForEntity |
Post | postForEntity, postForObject, postForLocation |
PUT | put |
any | exchange, execute |
DELETE | delete |
HEAD | headForHeaders |
OPTIONS | optionsForAllow |
The above is the main API of RestTemplate, most of which will be explained in detail in the following code.
All usage of Get request
Get request method:
- url splicing parameters
- url splicing parameter "placeholder method"
- Get response entity object response status code
/** * Test get request */ @Test public void test1(){ /** * getForObject * * Required url for address to be requested for parameter 1 * Parameter 2 response data type is String or Map and other required items * Parameter 3 request to carry parameter optional * * getForObject The return value of the method is the response data of the called interface */ String result = restTemplate.getForObject("http://localhost:8802/testRestGet?username=zhangsan", String.class); System.out.println(result); /** * getForEntity Method * Required url for address to be requested for parameter 1 * Parameter 2 response data type is String or Map and other required items * Parameter 3 request to carry parameter optional * * The return value type is ResponseEntity * * Response entity can be used to obtain response data, response status code and other information */ ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://localhost:8802/testRestGet?username=zhangsan", String.class); System.out.println("Get the status of the response:"+responseEntity.getStatusCode()); System.out.println("Get the data of the response:"+responseEntity.getBody()); /** * Transfer parameters through Map */ Map map= new HashMap(); map.put("name","zhangsan"); String resultId = restTemplate.getForObject("http://localhost:8802/testRestGet?username={name}", String.class,map); System.out.println(resultId); }
It should be noted that parameters are passed through Map
When executing the test code, you can see the following effects:
All usage of Post request
Three situations of post request
- Simulation carry form parameters
- url splicing parameters
- After the request is successful, get the jump address
/** * Test Post request */ @Test public void test2(){ /** * postForObject Return data with response value * Parameter 1 url to request address * Parameter 2 encapsulates the request parameters through the LinkedMultiValueMap object to simulate the form parameters, which are encapsulated in the request body * Parameter 3 type of response data */ LinkedMultiValueMap<String, String> request = new LinkedMultiValueMap<>(); request.set("username","zhangsan"); String result = restTemplate.postForObject("http://localhost:8802/testRestPost",request,String.class); System.out.println(result); /** * Post Parameters can also be spliced when requesting, in the same way as Get * The example is as follows: encapsulate data by map, and splice parameters to url by placeholder * Same as Get request url splicing */ Map map = new HashMap(); map.put("password","123456"); String result2 = restTemplate.postForObject("http://localhost:8802/testRestPost?password={password}",request, String.class,map); /** * postForLocation This API is different from the first two * * Login or registration are all post requests, and after these operations are completed? Most of them jump to other pages. In this scenario, you can use postForLocation to submit data and get the returned URI * Address to jump in response parameter */ URI uri = restTemplate.postForLocation("http://localhost:8802/testRestPostLocation", request); System.out.println("postForLocation The requested address is:"+uri); }
Perform the test method with the following effects:
Tips: delete, put and other request methods are similar to Get and Post, which can be done by imitating Get and Post.
How to set request headers for Get and Post
Set the request header "suitable for Get, Post and other requests" in general mode
1. Create ClientHttpRequestInterceptor class and add request header
package com.lby; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; import java.io.IOException; /** * @author luxiaoyang * @create 2020-03-20-20:37 */ public class UserAgentInterceptor implements ClientHttpRequestInterceptor { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { HttpHeaders headers = request.getHeaders(); // Set request header parameters headers.add(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"); return execution.execute(request, body); } }
2. Use request header when Get request
/** * General mode set request header */ @Test public void test3(){ /** * RestTemplate Set interceptor using request header */ restTemplate.setInterceptors(Collections.singletonList(new UserAgentInterceptor())); /** * Normal send request */ String result = restTemplate.getForObject("http://localhost:8802/testRestGet?username=zhangsan", String.class); System.out.println(result); }
The second way for Post request to set request header
The second parameter of post request is request. You can build HttpEntity object according to the request header + request parameter, and pass this in as the request request parameter of post. The specific code is as follows:
/** * Post Method setting request header */ @Test public void test4(){ //1. Set request header parameters HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.add(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"); //2. Carry parameters in the parameter request body of the simulation form MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>(); requestBody.add("username", "zhangsan"); //3. Encapsulate HttpEntity object HttpEntity<MultiValueMap> requestEntity = new HttpEntity<MultiValueMap>(requestBody, requestHeaders); RestTemplate restTemplate = new RestTemplate(); //4. Send Post request ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost:8802/testRestPost", requestEntity, String.class); System.out.println(responseEntity.getBody()); }
summary
Download address of all sample codes: https://gitee.com/bingqilinpeishenme/boot-demo/tree/master
Congratulations on the completion of this chapter, applaud for you! If this article is helpful to you, please like it, comment and forward it. It's very important for the author. Thank you.
Let's review the learning objectives of this article again
- Master the use of RestTemplate in SpringBoot
To learn more about SpringBoot, stay tuned for this series of tutorials.
Welcome to my official account: Mr. Lu's Java notes will be updated in Java technology tutorials and video tutorials, Java learning experience, Java interview experience and Java practical development experience.