Sub topic 1
HTTP in Brief: Requests, Responses, Methods and Status Codes
Prerequisites
This chapter assumes Java 11 or later, basic HTTP knowledge, and familiarity with checked exceptions such as IOException and InterruptedException.
The HTTP Conversation
HTTP is a protocol for exchanging messages between a client and a server. A client sends a request to a server. The server sends back a response.
A request usually contains:
- A URI, which identifies the resource, such as
https://example.com/items. - An HTTP method, which describes the intended operation.
- Request headers, which provide metadata.
- An optional request body, such as JSON data.
A response contains:
- A status code, which reports the result.
- Response headers, such as the content type.
- An optional response body.
Common methods describe common operations:
| Method | Typical purpose | Request body |
|---|---|---|
| GET | Read a resource | Usually no |
| POST | Create or submit data | Often yes |
| PUT | Replace a resource | Often yes |
| DELETE | Remove a resource | Usually no |
A status code belongs to a class. Codes from 200 through 299 usually mean success. Codes from 300 through 399 indicate redirection. Codes from 400 through 499 indicate a client-side problem, such as an invalid request or missing authentication. Codes from 500 through 599 indicate a server-side failure.
The Three Core Java Types
The Java HTTP API in java.net.http models the conversation with three main types:
HttpClientmanages connections and sends requests.HttpRequestdescribes one request.HttpResponse<T>contains the result.Tis the type used for the response body.
The following program creates one client, builds a GET request, sends it, and reads the response body as a String.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class BasicHttp {
public static void main(String[] args)
throws java.io.IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/"))
.header("Accept", "text/html")
.GET()
.build();
HttpResponse<String> response = client.send(
request,
HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + response.statusCode());
System.out.println(response.body());
}
}HttpRequest objects are immutable. The builder configures the URI, method, headers, and body before build() creates the request. The send method is synchronous: the current thread waits for the response. BodyHandlers.ofString() tells the client to collect the response body as text.
A shared HttpClient is normally reused for many requests. It can manage connection reuse and can also send asynchronous requests.
Exercise
Does HttpClient throw an exception automatically when a server returns HTTP 404?
Show answer
No. It returns an HttpResponse, so the program must inspect response.statusCode() and decide how to handle the 404.