Java HTTP Requests

Making web requests in Java applications

🌐 What are HTTP Requests?

HTTP requests in Java enable communication with web servers and APIs. You can send GET, POST, PUT, DELETE requests to retrieve data, submit forms, and interact with web services easily.


// Simple HTTP GET request
URL url = new URL("https://api.example.com/data");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
                                    

HTTP Request Components

📄

GET Request

Retrieve data from server

connection.setRequestMethod("GET");
📤

POST Request

Send data to server

connection.setRequestMethod("POST");
🏷️

Headers

Request metadata and configuration

connection.setRequestProperty("Content-Type", "application/json");
📊

Response

Server response data and status

int responseCode = connection.getResponseCode();

🔹 Simple GET Request

Retrieve data from a web server:

import java.net.*;
import java.io.*;

public class HTTPGetExample {
    public static void main(String[] args) {
        try {
            // Create URL object
            URL url = new URL("https://jsonplaceholder.typicode.com/posts/1");
            
            // Open connection
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            
            // Set request method
            connection.setRequestMethod("GET");
            
            // Set request headers
            connection.setRequestProperty("User-Agent", "Java HTTP Client");
            
            // Get response code
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            
            // Read response
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream()));
            
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            
            // Print response
            System.out.println("Response: " + response.toString());
            
            // Close connection
            connection.disconnect();
            
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Output:

Response Code: 200

Response: {"userId":1,"id":1,"title":"sunt aut facere..."}

🔹 POST Request with Data

Send data to a server using POST method:

import java.net.*;
import java.io.*;

public class HTTPPostExample {
    public static void main(String[] args) {
        try {
            // Create URL
            URL url = new URL("https://jsonplaceholder.typicode.com/posts");
            
            // Open connection
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            
            // Configure POST request
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);
            
            // Create JSON data
            String jsonData = "{"
                + "\"title\": \"My New Post\","
                + "\"body\": \"This is the post content\","
                + "\"userId\": 1"
                + "}";
            
            // Write data to request body
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonData.getBytes("utf-8");
                os.write(input, 0, input.length);
            }
            
            // Get response
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            
            // Read response
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream()));
            
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            
            System.out.println("Response: " + response.toString());
            
            connection.disconnect();
            
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

🔹 HTTP Client (Java 11+)

Modern HTTP client introduced in Java 11:

import java.net.http.*;
import java.net.*;
import java.time.Duration;

public class ModernHTTPClient {
    public static void main(String[] args) {
        try {
            // Create HTTP client
            HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .build();
            
            // Create GET request
            HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
                .header("User-Agent", "Java HTTP Client")
                .timeout(Duration.ofSeconds(30))
                .GET()
                .build();
            
            // Send request and get response
            HttpResponse response = client.send(request,
                HttpResponse.BodyHandlers.ofString());
            
            // Print results
            System.out.println("Status Code: " + response.statusCode());
            System.out.println("Headers: " + response.headers().map());
            System.out.println("Body: " + response.body());
            
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

🔹 Async HTTP Request

Make asynchronous HTTP requests (Java 11+):

import java.net.http.*;
import java.net.*;
import java.util.concurrent.CompletableFuture;

public class AsyncHTTPExample {
    public static void main(String[] args) {
        try {
            // Create HTTP client
            HttpClient client = HttpClient.newHttpClient();
            
            // Create request
            HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
                .build();
            
            // Send async request
            CompletableFuture> futureResponse = 
                client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
            
            // Handle response asynchronously
            futureResponse.thenAccept(response -> {
                System.out.println("Async Response Code: " + response.statusCode());
                System.out.println("Async Response Body: " + response.body());
            }).join(); // Wait for completion
            
            System.out.println("Request completed!");
            
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

🔹 HTTP Response Codes

Understanding common HTTP response status codes:

Success Codes (2xx):

  • 200 OK: Request successful
  • 201 Created: Resource created successfully
  • 204 No Content: Success but no content to return

Client Error Codes (4xx):

  • 400 Bad Request: Invalid request format
  • 401 Unauthorized: Authentication required
  • 404 Not Found: Resource not found

Server Error Codes (5xx):

  • 500 Internal Server Error: Server error
  • 503 Service Unavailable: Server temporarily unavailable

🔹 Error Handling

Handle HTTP errors and exceptions properly:

import java.net.*;
import java.io.*;

public class HTTPErrorHandling {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://jsonplaceholder.typicode.com/posts/999");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            
            int responseCode = connection.getResponseCode();
            
            if (responseCode >= 200 && responseCode < 300) {
                // Success - read normal response
                BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()));
                // ... read response
                System.out.println("Request successful!");
                
            } else if (responseCode >= 400 && responseCode < 500) {
                // Client error
                System.out.println("Client error: " + responseCode);
                BufferedReader errorReader = new BufferedReader(
                    new InputStreamReader(connection.getErrorStream()));
                // ... read error response
                
            } else if (responseCode >= 500) {
                // Server error
                System.out.println("Server error: " + responseCode);
            }
            
            connection.disconnect();
            
        } catch (MalformedURLException e) {
            System.out.println("Invalid URL: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("Network error: " + e.getMessage());
        }
    }
}

🧠 Test Your Knowledge

Which HTTP method is used to retrieve data from a server?