Client, Server and HTTP

Request and Response

The web is a conversation between a client (browser, mobile app, React app, Postman) and a server (your Spring Boot app). They talk using HTTP (HyperText Transfer Protocol). The client sends a request; the server sends back a response.

Client (React / Postman)                         Server (Spring Boot :8080)
        |  GET /api/products/1 HTTP/1.1                     |
        |  Accept: application/json        ---------->      |
        |                                                   |  find product 1
        |  HTTP/1.1 200 OK                                  |
        |  Content-Type: application/json  <----------      |
        |  {"id":1,"name":"Boat Rockerz 450",...}           |

What a Raw HTTP Message Looks Like

HTTP is just text. A request has a request line (method, path, version), headers, a blank line and an optional body. A response has a status line, headers and a body.

POST /api/cart HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Accept: application/json

{"productId": 1, "quantity": 2}

HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/cart/7

{"id": 7, "productId": 1, "quantity": 2}

Parsing a Request in Plain Java

Example

Spring Boot (through Tomcat) reads this text for you. To see there is no magic, here is a tiny parser for the request line and headers:

import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String raw = """
            GET /api/products/1 HTTP/1.1
            Host: localhost:8080
            Accept: application/json
            User-Agent: PostmanRuntime/7.39.0
            """;

        String[] lines = raw.strip().split("\\R");
        String[] requestLine = lines[0].split(" ");
        Map<String, String> headers = new LinkedHashMap<>();
        for (int i = 1; i < lines.length; i++) {
            int colon = lines[i].indexOf(':');
            headers.put(lines[i].substring(0, colon), lines[i].substring(colon + 1).trim());
        }

        System.out.println("Method : " + requestLine[0]);
        System.out.println("Path   : " + requestLine[1]);
        System.out.println("Version: " + requestLine[2]);
        headers.forEach((k, v) -> System.out.println("Header " + k + " = " + v));
    }
}

Output

Method : GET
Path   : /api/products/1
Version: HTTP/1.1
Header Host = localhost:8080
Header Accept = application/json
Header User-Agent = PostmanRuntime/7.39.0