Trabalho com Rede e API HTTP em Java: Guia Detalhado
What is it and why? (a real-life analogy)
Imagine you are sitting in a cozy cafe and want to order a pizza. You don't go to the kitchen yourself, you don't get into the oven, and you don't touch the dough. Instead, you call the waiter, say: "A Margherita, please," and after a while, you receive the finished dish.
Working with the network and HTTP API in Java is exactly the same. Your program (the client) is you at the table. The server on the internet is the restaurant kitchen. And the HTTP request is the waiter who delivers your order and brings back the response.
Why is this needed? Imagine you are writing a weather forecast application. Your program cannot "see" the clouds or measure the temperature itself. But it can send a request to the weather service's server, get data from there (a JSON file with degrees and precipitation), and display it to the user.
This is exactly how the following work:
- Social media authorization (your program asks the VKontakte server: "Check the password!")
- Online banking (requesting an account balance)
- Multiplayer games (sending character coordinates)
- Any website you open in your browser
💡 Important: HTTP API is not "magic," but simply a set of rules (a protocol) by which programs communicate over the internet. Just as waiters in different restaurants know that plates should be carried on a tray, programs know that data must be transmitted in a specific format.
Theory: how it works from the inside
Let's look "under the hood" and understand what happens when a Java program makes an HTTP request.
1. Client-server architecture
In any network communication, there are two sides:
- Client — the one who requests data (your Java program)
- Server — the one who stores and provides that data (e.g., a Google server)
The client and server can be on different continents. They communicate over the internet using the HTTP protocol (HyperText Transfer Protocol).
2. Structure of an HTTP request
When your program "knocks" on the server, it sends a message that consists of three parts:
- Start line — contains the method (GET, POST, etc.) and the address (URL)
- Headers — additional information: which browser, what data format we accept, if there is authorization
- Body — the data itself (e.g., login and password during registration). Not all requests have one
3. HTTP methods (verbs)
The most popular methods are like commands for the server:
| Method | What it does | Real-life analogy |
|---|---|---|
| GET | Requests data (reading) | "Give me the menu" |
| POST | Sends new data (creation) | "Write down my order" |
| PUT | Updates existing data | "Replace my pizza with another one" |
| DELETE | Deletes data | "Cancel my order" |
4. Response codes (statuses)
The server doesn't stay silent in response — it always sends a three-digit code:
| Code | Meaning | What it means |
|---|---|---|
| 200 | OK | Everything is fine, here is your data |
| 201 | Created | Created successfully |
| 301 | Moved Permanently | The page has moved to a different address |
| 400 | Bad Request | You sent something wrong (client error) |
| 401 | Unauthorized | Authorization required (you didn't identify yourself) |
| 403 | Forbidden | Access denied (you don't have permission) |
| 404 | Not Found | This address does not exist |
| 500 | Internal Server Error | The server broke down (server error) |
⚠️ Remember: Codes 2xx are success, 4xx means you did something wrong, 5xx means problems on the server. If you see 404 — check the URL. If 500 — wait, the server might be overloaded.
5. Data formats: JSON and XML
Servers rarely provide data in the form of a beautiful HTML page. More often they use JSON (JavaScript Object Notation) — a lightweight text format similar to a Java object:
{
"name": "Ivan",
"age": 25,
"isStudent": false
}
Java doesn't understand JSON "out of the box," so we use special libraries (e.g., Gson or Jackson) to convert JSON to a Java object and vice versa.
Syntax in Java: all forms and options
In Java, there are several ways to work with HTTP. We'll look at the two most popular:
- HttpURLConnection — a built-in class (doesn't require installing libraries)
- HttpClient — a modern API (introduced in Java 11)
HttpURLConnection (old but reliable)
This class lives in the java.net package. It's a bit cumbersome, but it works everywhere, even on very old versions of Java.
Main steps:
- Create a URL object
- Open a connection (get an HttpURLConnection)
- Configure the method (GET, POST, etc.)
- Send the request
- Read the response
- Close the connection
HttpClient (new, convenient)
Introduced in Java 11. It's more modern, supports asynchronous requests, and works in a "Builder" style.
Main classes:
java.net.http.HttpClient— the client itselfjava.net.http.HttpRequest— the requestjava.net.http.HttpResponse— the response