HTTP Requests in Java: A Complete Guide with Examples
#HTTP Requests in Java: A Complete Guide with Examples
Introduction
In modern applications, communicating with web servers and APIs is a common requirement. Whether you are building a REST API client, fetching data from a server, or sending POST requests, Java provides multiple ways to handle HTTP requests.
In this guide, we will cover the basics of making HTTP requests in Java, explore different approaches, and provide real-world GET and POST examples.
Java provides multiple options for sending HTTP requests:
HttpURLConnection (Core Java) – Simple, built-in way to handle HTTP requests.
HttpClient (Java 11+) – Modern, efficient, and feature-rich API.
Third-party libraries (OkHttp, Apache HttpClient) – Widely used in enterprise-level applications.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class GetRequestExample {
public static void main(String[] args) throws Exception {
URL url = new URL("https://jsonplaceholder.typicode.com/posts/1");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response: " + response.toString());
}
}
✅ Output: JSON response from API.
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostRequestExample {
public static void main(String[] args) throws Exception {
URL url = new URL("https://jsonplaceholder.typicode.com/posts");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setDoOutput(true);
String jsonInput = "{\"title\":\"Java HTTP Request\",\"body\":\"Learning POST request in Java\",\"userId\":1}";
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonInput.getBytes("utf-8");
os.write(input, 0, input.length);
}
System.out.println("Response Code: " + conn.getResponseCode());
}
}
✅ Output: 201 Created
response with new resource ID.
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Response: " + response.body());
}
}
✅ Output: JSON response from API.
Feature | HttpURLConnection | HttpClient (Java 11+) |
---|---|---|
Availability | Java 1.1+ | Java 11+ |
Ease of Use | Verbose | Simple & Modern |
Async Support | ❌ No | ✅ Yes |
Performance | Moderate | High |
Consuming REST APIs
Fetching data from web services
Sending JSON/XML payloads
Integrating with payment gateways, authentication APIs
Building microservices communication
✔ Use HttpClient (Java 11+) for modern projects.
✔ Set appropriate headers (Content-Type
, Authorization
).
✔ Handle timeouts and exceptions.
✔ Prefer third-party libraries (OkHttp, Apache HttpClient) for large-scale apps.
Java offers multiple ways to perform HTTP requests, from the traditional HttpURLConnection
to the modern HttpClient
. By mastering these, developers can easily connect to REST APIs, web services, and cloud-based applications.
🔑 Target SEO Keywords:
HTTP requests in Java, Java HttpURLConnection example, Java HttpClient tutorial, Java GET request, Java POST request, REST API call in Java, networking in Java