SoFunction
Updated on 2025-03-03

Several ways SpringBoot calls external interfaces

Calling with FeignClient

FeignClient calls are mostly used in microservice development, and interface calls between services. It calls HTTP requests in Java interface annotation, making calling between services simple

1. Introduce dependencies in the user

<!-- Feignannotation hereopenFeignThe version you need to use withSpringBootmatch-->
<dependency>
    <groupId></groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <!-- <version>4.0.1</version> -->
</dependency>

2. Service interface caller

2.1. Add @EnableFeigncliens annotation to the startup class

import ;
import ;
import ;

@SpringBootApplication
@EnableFeignClients
public class StudyfeignApplication {

    public static void main(String[] args) {
        (, args);
        ("Project starts successfully");
    }

}

2.2. Write the Feign interface call service controller layer

import ;
import ;
import ;
import ;
import ;

@RestController
@RequestMapping("feign")
public class SysUserController {

    @Autowired
    private SysUserClient sysUserClient;

    @PostMapping("getUserId")
    public void getUserId(String userId){
        (userId);
    }

}

2.3. The service interface calls the service layer

Feign's client needs to be expressed using the @FeignClient annotation, so that only when scanning, it is known that this is a feign client. @FeignClient has two most commonly used properties, one name, which is used to define a unique name for the client, and the other is the url, which is used to define the remote address called by the client. The contents in the url can be written in the configuration file for easy management

@Service
@FeignClient(name = "feign-service",url = "${master-getuserbyId}")
public interface SysUserClient {

    @PostMapping("/master/test")
    String getUserById(String id);

}

The configuration in the following

server:
  port: 8081
master-getuserbyId: http://localhost:8080

3. Service interface provider

There are no special requirements for interface providers, just like normal interface development

4. Explanation

It should be noted that in the interface caller, you can continue to expand the service layer, write the service implementation layer, and further expand.

import ;

@Service
public class SysUserClientImpl implements SysUserClient{
    @Override
    public String getUserById(String id) {
        return "";
    }
}

Called using RestTemplate

Several commonly used methods in RestTemplate: getForObject(), getForEntity(), postForObject(), and postForEntity(). Among them, the getForObject() and getForEntity() methods can be used to send GET requests

1. Introduce dependencies

  <dependency>
      <groupId></groupId>
      <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

2. RestTemplateConfig configuration class

The HTTP library corresponding to the SimpleClientHttpRequestFactory class is the HttpUrlConnection that comes with JDK. Of course, we can use other HTTP libraries according to our own needs, such as HttpComponentsAsyncClientHttpRequestFactory

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        (5000);//Unit is ms        (5000);//Unit is ms        return factory;
    }
}

3. Interface call

@RestController
public class TestRestTemplate {
    @Resource
    private RestTemplate restTemplate;

    @GetMapping(value = "/saveUser")
    public void saveUser(String userId) {
        String url = "http://127.0.0.1:8080/master/test";
        Map map = new HashMap<>();
        ("userId", "hy001");
        String results = (url, map, );
    }
  }

Calling with WebClient

Spring 3.0 introduced RestTemplate, but in the later official source code, RestTemplate may be deprecated in future versions. The so-called replacement of RestTemplate introduced WebClient as an asynchronous non-blocking and responsive HTTP client in Spring 5.

1. Introduce dependencies

<dependency>
      <groupId></groupId>
      <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

2. Interface call example

public class TestWebClient {
    @Test
    public void doGet() {
        String userId = "Guo Guo";
        String url = "http://127.0.0.1:8080/master/test/getSysUserById?userId={userId}";
        Mono&lt;String&gt; mono = WebClient
                //Create a WebClient instance                .create()
                //Method call, WebClient provides a variety of methods                .get()
                //Request url                .uri(url, userId)
                //Get the response result                .retrieve()
                //Convert the result to the specified type                .bodyToMono();
        //Return the final result: block is blocked/subscribe() non-blocking gets the response result        ("Response Results:" + ());
    }
    @Test
    public void doPost() {
        Map map = new HashMap&lt;&gt;();
        ("name", "Guo Guo");
        String requestBody = (map);
        String url = "http://127.0.0.1:8080/master/test/saveUser";
        Mono&lt;String&gt; mono = WebClient
                //Create a WebClient instance                .create()
                //Method call, WebClient provides a variety of methods                .post()
                //Request url                .uri(url)
                //Specify that the requested Content-Type is JSON                .contentType(MediaType.APPLICATION_JSON)
                //Use bodyValue method to pass the request body                .bodyValue(requestBody)
                //Get the response result                .retrieve()
                //Convert the result to the specified type                .bodyToMono();
        //Return the final result: block is blocked/subscribe() non-blocking gets the response result        ("Response Results:" + ());
    }
}

In the above doPost request, our request interface parameter is a map, but it needs to be converted to JSON format and passed, because WebClient is serialized using JSON by default.

Called using Apache HttpClient

public class TestHttpClient {
    @Test
    public void doGet() throws IOException {
        //Step 1: Create an httpClient instance        CloseableHttpClient httpClient = ();
        //Step 2: Create an HTTP request        HttpGet httpGet = new HttpGet("http://127.0.0.1:8094/masterdata/sysUser/getSysUserById?userId=Guo Guo");        //Step 3: Send a request and get response data        CloseableHttpResponse response = (httpGet);
        //Step 4: Process the response data        HttpEntity entity = ();
        String result = (entity);
        //Step 5: Close httpClient and response        ();
        ();
    }
    @Test
    public void doPost() throws IOException {
        //Step 1: Create an httpClient instance        CloseableHttpClient httpClient = ();
        //Step 2: Create an HTTP request        HttpPost httpPost = new HttpPost("http://127.0.0.1:8094/masterdata/sysUser/saveUser");
        //Step 3: Set the request volume data and use JSON format        Map map = new HashMap&lt;&gt;();
        ("name", "Guo Guo");
        String requestBody = (map);
        StringEntity stringEntity = new StringEntity(requestBody, "UTF-8");
        ("application/json");
        (stringEntity);
        
        //Step 4: Send a request and get response data        CloseableHttpResponse response = (httpPost);
        //Step 5: Process the response data        HttpEntity entity = ();
        String result = (entity);
        //Step 5: Close httpClient and response        ();
        ();
    }
}

Called using HttpURLConnection

public class TestHttpURLConnection {

    @Test
    public void doGet() throws IOException {
        String userId = "Guo Guo";  // Parameter value        userId = (userId, "UTF-8"); // URL encoding of parameter values        //Step 1: Create a URL object        URL url = new URL("http://127.0.0.1:8094/masterdata/sysUser/getSysUserById?userId=" + userId);
        //Step 2: Open the connection        HttpURLConnection conn = (HttpURLConnection) ();
        //Step 3: Set the request method        ("GET");
        //Step 4: Read the response content        BufferedReader reader = new BufferedReader(new InputStreamReader(()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = ()) != null) {
            (line);
        }
        ();
        (());
    } 
    @Test
    public void doPost() throws IOException {
        //Create URL object        URL url = new URL("http://127.0.0.1:8094/masterdata/sysUser/saveUser");
        //Open the connection        HttpURLConnection conn = (HttpURLConnection) ();
        //Set request method        ("POST");
        // Set request header        ("Content-Type", "application/json");
        //Enable output stream        (true);
        //Set request volume data        Map map = new HashMap&lt;&gt;();
        ("name", "Guo Guo");
        String requestBody = (map);
        //Send request volume data        try (DataOutputStream outputStream = new DataOutputStream(())) {
            ((StandardCharsets.UTF_8));
        }

        //Read the response content        BufferedReader reader = new BufferedReader(new InputStreamReader(()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = ()) != null) {
            (line);
        }
        ();
        (());
    } 
  }

Called using OkHttp

1. Introduce dependencies

&lt;!--okhttprely--&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;.okhttp3&lt;/groupId&gt;
    &lt;artifactId&gt;okhttp&lt;/artifactId&gt;
    &lt;version&gt;4.0.0&lt;/version&gt;
  &lt;/dependency&gt;

2. Sample code

public class TestOkHttp {

    @Test
    public void doGet() throws IOException {
        OkHttpClient client = new OkHttpClient();
        String url = "http://127.0.0.1:8080/master/test/getSysUserById?userId=Guo Guo";        Request request = new ().url(url).build();
        try (Response response = (request).execute()) {
            ResponseBody body = ();
            (());
        }
    }

    @Test
    public void doPost() throws IOException{
        OkHttpClient client = new OkHttpClient();
        String url = "http://127.0.0.1:8080/master/test/saveUser";
        MediaType mediaType = ("application/json; charset=utf-8");
        //RequestBody request to enter the parameter        Map map = new HashMap&lt;&gt;();
        ("name", "admin");
        RequestBody requestBody = (mediaType, (map));
        Request request = new ()
                .url(url)
                .post(requestBody)
                .build();
        try (Response response = (request).execute()) {
            ResponseBody body = ();
            (());
        }
    }
}

Called using AsyncHttpClient

1. Introduce dependencies

<dependency>
      <groupId></groupId>
      <artifactId>async-http-client</artifactId>
      <version>2.12.3</version>
</dependency>

2. Sample code

public class TestAsyncHttpClient {
    @Test
    public void doGet() throws IOException {
        try (AsyncHttpClient client = new DefaultAsyncHttpClient();) {
            BoundRequestBuilder requestBuilder = ("http://127.0.0.1:8080/master/test/getSysUserById?userId=hy001");
            CompletableFuture&lt;String&gt; future = ()
                    .toCompletableFuture()
                    .thenApply(Response::getResponseBody);
            //Use join to wait for the response to complete            String responseBody = ();
            (responseBody);
        }
    }
    @Test
    public void doPost() throws IOException {
        try (AsyncHttpClient client = new DefaultAsyncHttpClient();) {
            BoundRequestBuilder requestBuilder = ("http://127.0.0.1:8094/8080/master/test/saveUser");
            //RequestBody request to enter the parameter            Map map = new HashMap&lt;&gt;();
            ("name", "admin");
            String requestBody = (map);
            ("Content-Type", "application/json");
            (requestBody);
            CompletableFuture&lt;String&gt; future = ()
                    .toCompletableFuture()
                    .thenApply(Response::getResponseBody);
            //Use join to wait for the response to complete            String responseBody = ();
            (responseBody);
        }
    }
  }

This is the end of this article about several ways SpringBoot calls external interfaces. For more related content on SpringBoot calling external interfaces, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!