Sub topic 1
HTTP in brief: requests, responses, methods and status codes
This chapter covers the HTTP model that the rest of the tutorial builds on. Every type in java.net.http maps onto a part of it: a request has a method, a URI, headers and an optional body, and a response has a status code, headers and an optional body. Knowing which part is which makes the API easier to read and its failure modes easier to predict.
Prerequisites
This chapter assumes you have:
- Java 11 or later syntax and the standard library.
- A basic idea of what a web server and a URL are.
- Familiarity with try/catch and checked exceptions. Later chapters use them heavily.
You do not need to have used HttpClient before. This chapter contains no calls to it. It only defines the vocabulary.
The request/response exchange
HTTP is a request/response protocol. A client sends one request, and the server answers with one response. The server never sends a response the client did not ask for. Each exchange is independent, so the protocol itself keeps no memory between exchanges. Anything that looks like a session, such as a login, is built on top with headers or cookies.
On the wire, a request is plain text, followed by an optional body:
POST /items HTTP/1.1
Host: api.example.com
Content-Type: application/json
Accept: application/json
Content-Length: 17
{"name":"widget"}The response has the same shape:
HTTP/1.1 201 Created
Content-Type: application/json
Location: /items/42
Content-Length: 31
{"id":42,"name":"widget"}The parts are:
- Start line. A request has a method, a target and a protocol version. A response has a version, a status code and a reason phrase.
- Headers. These are name/value pairs. Names are case-insensitive, and the same name can appear more than once.
- Blank line. This separates the headers from the body.
- Body. It is optional, and its format is described by
Content-Type.
In the Java API, the method, URI, headers and body publisher make up an HttpRequest. The status code, headers and decoded body make up an HttpResponse.
Methods
The method tells the server what the client wants to do with the resource named by the URI. Two properties of methods matter in practice:
- A method is safe if it is meant only to read data and not change server state.
- A method is idempotent if repeating the same request leaves the server in the same state as sending it once.
| Method | Typical use | Safe | Idempotent | Request body |
|---|---|---|---|---|
| GET | Read a resource | Yes | Yes | Not normally used |
| HEAD | Read headers only, no response body | Yes | Yes | No |
| POST | Create a resource or trigger an action | No | No | Yes |
| PUT | Replace a resource | No | Yes | Yes |
| PATCH | Partially modify a resource | No | Not guaranteed | Yes |
| DELETE | Remove a resource | No | Yes | Rarely |
Idempotency decides whether a failed request can be retried safely. If a POST times out, you do not know whether the server processed it, and sending it again may create a duplicate. Retries come up again in the chapter on retries and backoff.
Headers you will meet constantly
| Header | Direction | Purpose |
|---|---|---|
| `Content-Type` | Both | Format of the body, for example `application/json` |
| `Accept` | Request | Formats the client is willing to receive |
| `Authorization` | Request | Credentials, for example `Bearer <token>` |
| `User-Agent` | Request | Identifies the client software |
| `Location` | Response | Target of a redirect, or the URI of a created resource |
| `Retry-After` | Response | How long to wait before trying again |
Content-Type describes the body that travels with the message, and Accept describes what the client wants back. Sending a JSON body without Content-Type: application/json is a common cause of 415 Unsupported Media Type or 400 Bad Request.
Status codes
The first digit of the status code gives the class of the result.
| Range | Meaning | Examples |
|---|---|---|
| 1xx | Informational | 100 Continue |
| 2xx | Success | 200 OK, 201 Created, 204 No Content |
| 3xx | Redirection | 301 Moved Permanently, 302 Found, 304 Not Modified |
| 4xx | Client error: the request is at fault | 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many Requests |
| 5xx | Server error: the server failed | 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout |
Several details trip people up:
- A status code is a successful HTTP exchange. A 404 or 500 means the client and server communicated correctly and the server said no. Java's
HttpClientreturns such a response normally. It does not throw an exception. The error handling chapter covers this in detail. - 204 No Content means success with an empty body. Parsing the body of a 204 as JSON fails.
- 401 versus 403. 401 means the server does not know who you are, or your credentials are invalid. 403 means it knows who you are and refuses anyway.
- 429 and 503 often carry a
Retry-Afterheader. Honor it before retrying. - 4xx errors usually should not be retried. Resending an invalid request gives the same answer. 5xx errors and 429 are the usual retry candidates, and only if the method is idempotent or the server supports idempotency keys.
- 3xx responses come with a
Locationheader. Whether a client follows them automatically is a client setting. The redirect chapter shows howHttpClienthandles it.
Classifying a status in Java
Most code that calls an API starts with a check of the status class. This standalone program shows the integer arithmetic involved, with no HTTP call at all.
public class StatusClass {
static String classify(int status) {
if (status >= 200 && status < 300) return "success";
if (status >= 300 && status < 400) return "redirect";
if (status >= 400 && status < 500) return "client error";
if (status >= 500 && status < 600) return "server error";
return "other";
}
public static void main(String[] args) {
int[] codes = {200, 204, 301, 404, 429, 503};
for (int code : codes) {
System.out.println(code + " -> " + classify(code));
}
}
}Running it prints one line per code, for example 404 -> client error. The same check appears in real client code in the error handling chapter.
Where failures happen
A call can fail in two different ways, and they surface differently in Java.
- No response arrives. The DNS lookup fails, the connection is refused, the connection drops, or a timeout expires. The client has nothing to return, so it signals this with an exception.
- A response arrives with a bad status. The exchange worked and the server reported a problem. You get a normal response object and have to inspect the status code yourself.
Keeping these two paths separate in your head prevents the most common bug in HTTP client code, which is treating "no exception" as "success".
How this maps onto the rest of the tutorial
- Methods, URI and headers are set when you build an
HttpRequest. - The request body comes from a
BodyPublisher. - The response body is decoded by a
BodyHandler. - The status code and response headers are read from the
HttpResponse. - Timeouts, redirects and the HTTP version are client-level or request-level settings.
The next chapter introduces the three core types and shows how each one maps onto the pieces described here.
Exercise
A client sends POST /orders and the connection times out before any response arrives. Why is it risky to simply send the same request again, and which status class from a server would normally tell you not to retry without changing the request?
Show answer
POST is not idempotent, and the timeout leaves it unknown whether the server already created the order, so a second request could create a duplicate. A 4xx status (client error) normally means the request itself is at fault, so resending it unchanged will fail the same way. Retries are mainly reasonable for 5xx or 429 responses, and only when the operation is idempotent or protected by an idempotency key.
Exercise
A call returns status 404 and your code prints the response body as if it were the requested data, with no exception thrown. What went wrong?
Show answer
Receiving a 404 is a completed HTTP exchange, so the client returns a normal response instead of throwing an exception. The code never checked the status code, so it treated an error response as success.