There is the concept of flying in the sky, there must be the realization of landing

  • The concept ten times is not as good as the code once, my friend, I hope you can type all the code cases in the article once

  • Like it before you look at it, make it a habit

SpringBoot illustrated tutorial series article directory

  1. SpringBoot+Mybatis environment setup
  2. Use “logback” and “log4j” to log.
  3. SpringBoot graphic tutorial 3 – “‘ first love ‘complex” integrated Jsp
  4. 4 – SpringBoot implementation file upload and download
  5. Use Aop in SpringBoot
  6. SpringBoot Tutorial 6 – The use of filters in SpringBoot
  7. SpringBoot tutorial 7 – The use of SpringBoot interceptor posture is available here
  8. SpringBoot integration with MBG code Generator
  9. SpringBoot import/export Excel “Apache Poi”
  10. SpringBoot graphic tutorials 10 – template export Excel export | | millions data image export “easypoi”
  11. SpringBoot integration with MybatisPlus
  12. Basic use of SpringData Jpa
  13. SpringBoot+IDEA implementation code hot deployment
  14. EasyExcel “Design for Millions of data Reads and writes”
  15. SpringBoot Tutorial 15 – How to handle project exceptions? “Jump 404 error page” “Global Exception Catch”
  16. SpringBoot Multi module development “Web” “Package”

preface

Question: How do I send an Http request to another Java program’s Controller method from Java code?

It seems to have hit a bit of an intellectual blind spot

In the previous code, Java programs are the requested party, the request is either Ajax, or browser, or Postman, etc. Today we will learn how to send Http requests through Java code.

The use of RestTemplate

Preparation “can be skipped without affecting tutorial learning”

Because we are sending a request through the RestTemplate for another project’s Controller layer method (interface), we first need a requested project. About this project, I have already set up good, yards cloud address is: https://gitee.com/bingqilinpeishenme/boot-demo/tree/master/boot-base-rest

There are three methods in the project, which are to test the Get request and Post request as follows

package com.lby.controller;



import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation. *.



/ * *

 * @author luxiaoyang

 * @createThe 2020-03-18-20:02

* /


@Controller

public class TestController {

    / * *

     * @GetMapping("testRestGet") The current method accepts only Get requests

* is equivalent to

     * @RequestMapping(path = "testRestGet",method = RequestMethod.GET)

* /


    @GetMapping("testRestGet")

    @ResponseBody

    public String testRestGet(String username){

        return "This is a Get request that accepts arguments:"+username;

    }



    / * *

     * @PostMapping("") The current method accepts only Post requests

* is equivalent to

     * @RequestMapping(path = "testRestPost",method = RequestMethod.POST)

* /


    @PostMapping("testRestPost")

    @ResponseBody

    public String testRestPost(String username){

        return This is a Post request that accepts arguments:+username;

    }



    / * *

* Tests postForLocation to the RestTemplate response URL

* /


    @PostMapping("testRestPostLocation")

    public String testRestPostLocation(String username){

        System.out.println(username);

        return "redirect:/success.html";

    }

}

Copy the code

What is the RestTemplate

Spring encapsulates the template class to send RestFul requests through Java code, and has built-in methods to send requests such as GET, post, and DELETE. In SpringBoot, you can directly use the spring-boot-starter-Web dependency.

Quick start

Determine the dependencies to import spring-boot-starter-Web in your project.

Step 1: Configure the RestTemplate

/ * *

* RestTemplate configuration

* /


@Configuration

public class RestTemplateConfig {



    @Bean

    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {

        return new RestTemplate(factory);

    }



    @Bean

    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {

        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();

        // Set timeout

        factory.setReadTimeout(5000);//ms

        factory.setConnectTimeout(15000);//ms

        return factory;

    }

}

Copy the code

Step 2: Send the request directly using the RestTemplate Api

In this step, we directly send the Get request in the test class, carry out a simple test, feel the effect, then more IN-DEPTH learning of the API.

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 requests

* /


    @Test

    public void test1(){

        / * *

         * getForObject

         * 

* Parameter 1 Specifies the URL of the address to be requested

* Parameter 2 Specifies whether the type of the response data is String or Map

* Parameter 3 This parameter is optional

         *

The return value of the getForObject method is the data in response to the called interface

* /


        String result = restTemplate.getForObject("http://localhost:8802/product/showProductById? id=1", String.class);



        System.out.println(result);

    }



}

Copy the code

The 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

These are the main apis of RestTemplate, most of which will be covered in more detail in subsequent code.

All ways to use a Get request

Get request mode:

  1. Url splicing parameter
  2. Url concatenation parameter “placeholder way”
  3. Get the response entity object “Response status code”
/ * *

* testgetrequest

* /

    @Test

    public void test1(){

/ * *

         * getForObject

         *

* parameters1The URL of the address to be requested is mandatory

* parameters2The type of the response data isStringThis field is mandatory, such as Map

* parameters3Request to carry parameters optional

         *

The return value of the getForObject method is the data in response to the called interface

* /

        String result = restTemplate.getForObject("http://localhost:8802/testRestGet? username=zhangsan".String.class);



        System.out.println(result);

/ * *

* getForEntity method

* parameters1The URL of the address to be requested is mandatory

* parameters2The type of the response data isStringThis field is mandatory, such as Map

* parameters3Request to carry parameters optional

         *

* Return value type ResponseEntity

         *

* ResponseEntity is the ResponseEntity that obtains the data for the response, the status code of the response, etc

* /

        ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://localhost:8802/testRestGet? username=zhangsan".String.class);



        System.out.println("Get response status:"+responseEntity.getStatusCode());



        System.out.println("Get response data:"+responseEntity.getBody());



/ * *

* Pass 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);



    }

Copy the code

Note that the parameter is passed in Map mode

When you execute the test class code, you can see the following:

All ways to use a Post request

There are three types of POST requests

  1. The simulation carries form parameters
  2. Url splicing parameter
  3. After a successful request, get the jump address
/ * *

* Test the Post request

* /

    @Test

    public void test2(){

/ * *

* postForObject returns the data for the response

* parameters1The URL for the address to request

* parameters2The LinkedMultiValueMap object encapsulates the request parameters to simulate the form parameters, encapsulated in the request body

* parameters3The type of response data

* /

        LinkedMultiValueMap<String.Stringrequest = new LinkedMultiValueMap<>();

        request.set("username"."zhangsan");



        String result = restTemplate.postForObject("http://localhost:8802/testRestPost".request.String.class);



        System.out.println(result);



/ * *

* Post request can also be used for parameter concatenation, using the method andGetThe same

* In the following example, a map encapsulates data and uses placeholders to concatenate parameters to a URL

* andGetRequest URL concatenation as well

* /

        Map map = new HashMap();

        map.put("password"."123456");



        String result2 = restTemplate.postForObject("http://localhost:8802/testRestPost? password={password}".request.

                String.class,map);



/ * *

* The postForLocation API is different from the first two

         *

* loginorRegistration is all POST requests, and what happens after that happens? Most of them just jump to another page, and in that case, you can use postForLocation, submit the data, and get the URI that's returned

* The address to jump to for the response parameter

* /

        URI uri = restTemplate.postForLocation("http://localhost:8802/testRestPostLocation".request);

        System.out.println("PostForLocation the requested address is:+uri);

    }

Copy the code

Execute the test method with the following effect:

Tips: Delete, put, and other requests are similar to Get and Post.

How do Get and Post set request headers

Common way to set the request header “suitable for Get, Post, etc.”

1. Create ClientHttpRequestInterceptor class, add the 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

 * @createThe 2020-03-20 - young

* /


public class UserAgentInterceptor implements ClientHttpRequestInterceptor {

    @Override

    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {



        HttpHeaders headers = request.getHeaders();

// Set the 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);

    }

}

Copy the code

2. Use headers for Get requests

  / * *

* Common way to set the request header

* /


    @Test

    public void test3()
{

        / * *

* RestTemplate sets the interceptor that uses the request header

* /


        restTemplate.setInterceptors(Collections.singletonList(new UserAgentInterceptor()));



        / * *

* Normal send requests

* /


        String result = restTemplate.getForObject("http://localhost:8802/testRestGet? username=zhangsan", String.class);



        System.out.println(result);

    }

Copy the code

Post request The second way to set the request header

The second argument to the Post Request is Request. You can construct an HttpEntity object based on the Request header and Request parameters and pass this as the Request argument to the Post Request. The specific code is as follows:

  / * *

* Post sets the 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. Mock form parameters request body carries parameters

        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();

        requestBody.add("username"."zhangsan");

        //3. Encapsulate the 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());

    }

Copy the code

conclusion

All the sample code download address: https://gitee.com/bingqilinpeishenme/boot-demo/tree/master

Congratulations on completing this chapter. A round of applause! If this article is helpful to you, please help to like, comment, retweet, this is very important to the author, thank you.

Let’s review the learning objectives of this article again

  • Learn how to use RestTemplate in SpringBoot

To learn more about SpringBoot, stay tuned for this series of tutorials.

Ask for attention, ask for likes, ask for retweets

Welcome to pay attention to my public account: Teacher Lu’s Java notes, will update Java technology graphic tutorials and video tutorials in the long term, Java learning experience, Java interview experience and Java actual combat development experience.