Java HttpClient Example: GET and POST Requests
Since Java 11 the standard library has a modern HTTP client: java.net.http.HttpClient. The example below starts a very small web server in the same program (with com.sun.net.httpserver), so it runs without internet, and then calls it with GET and POST.
Program
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws Exception {
// A tiny server for the test
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/hello", exchange -> {
byte[] body = "{\"message\":\"Hello from the server\"}".getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
server.createContext("/echo", exchange -> {
String text = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
byte[] body = ("You sent: " + text).getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(201, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
server.start();
int port = server.getAddress().getPort();
// The client
HttpClient client = HttpClient.newHttpClient();
HttpRequest get = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + "/hello"))
.GET()
.build();
HttpResponse<String> r1 = client.send(get, HttpResponse.BodyHandlers.ofString());
System.out.println("GET status: " + r1.statusCode());
System.out.println("Content-Type: " + r1.headers().firstValue("Content-Type").orElse("?"));
System.out.println("Body: " + r1.body());
HttpRequest post = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + "/echo"))
.header("Content-Type", "text/plain")
.POST(HttpRequest.BodyPublishers.ofString("name=Riya"))
.build();
HttpResponse<String> r2 = client.send(post, HttpResponse.BodyHandlers.ofString());
System.out.println("POST status: " + r2.statusCode());
System.out.println("Body: " + r2.body());
server.stop(0);
}
}
Output
GET status: 200
Content-Type: application/json
Body: {"message":"Hello from the server"}
POST status: 201
Body: You sent: name=Riya
Use it with a real API
Change the address to a real one, like https://api.example.com/items. The code is the same. Always set a timeout and check the status code:
HttpClient client = HttpClient.newBuilder()
.connectTimeout(java.time.Duration.ofSeconds(5))
.build();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.example.com/items"))
.timeout(java.time.Duration.ofSeconds(10))
.header("Accept", "application/json")
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
System.out.println(response.body());
}
client.send()waits for the answer.client.sendAsync()returns aCompletableFuture.- The JSON text must be read with a library like Jackson or Gson. The JDK has no JSON parser.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |