In the Spring family of frameworks, you can use code to send a request to another service, usually using restTemplate or Feign, but the underlying principles of both methods are explored today.

Set up the server first:

@RestController
public class Controller {
    @PostMapping("hello")
    public String hello() {
        return "hello"; }}Copy the code

Create a new SpringBoot service, create such a Controller, and start the service.

The service is then invoked using code to send a request:

    public static void main(String[] args) throws IOException {
        URI uri = URI.create("http://127.0.0.1:8080/hello");
        URL url = uri.toURL();
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(HttpMethod.POST.name());
        connection.setDoOutput(true);
        connection.connect();
        InputStream inputStream = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        System.out.println(reader.readLine());
    }
Copy the code

You can see that the console will return a “Hello”.

This is the basic API for Java code to send network requests, and the Spring framework further encapsulates it.

The next article will unpack what Spring does to encapsulate the basic API of the JDK.


Returns the directory