BLOG POSTS
    MangoHost Blog / Java HttpURLConnection Example – HTTP GET and POST Requests
Java HttpURLConnection Example – HTTP GET and POST Requests

Java HttpURLConnection Example – HTTP GET and POST Requests

Java’s HttpURLConnection is a fundamental class that serves as your go-to tool for making HTTP requests without adding external dependencies to your project. Whether you’re building a REST API client, integrating with third-party services, or just need to fetch data from a web endpoint, understanding how to leverage HttpURLConnection for both GET and POST requests is essential. This guide walks you through practical implementations, common gotchas, and real-world scenarios that’ll save you debugging time down the road.

How HttpURLConnection Works Under the Hood

HttpURLConnection sits on top of Java’s URL class and provides a protocol-specific URLConnection for HTTP and HTTPS URLs. It’s part of the java.net package and has been around since Java 1.1, making it rock-solid and available everywhere without external jar files.

The connection lifecycle follows a predictable pattern: create URL object, open connection, configure request properties, handle request body (for POST/PUT), read response, and clean up resources. The class handles connection pooling automatically and reuses connections when possible, though you can tune this behavior through system properties.

One thing that trips up newcomers is that HttpURLConnection is lazy – it doesn’t actually connect until you call getInputStream(), getOutputStream(), or getResponseCode(). This design lets you configure everything upfront before the network round-trip happens.

Step-by-Step HTTP GET Implementation

Here’s a bulletproof GET request implementation that handles the most common scenarios:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpGetExample {
    
    public static String performGetRequest(String urlString) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        
        // Configure the connection
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000); // 5 seconds
        connection.setReadTimeout(10000);   // 10 seconds
        connection.setRequestProperty("User-Agent", "Java-HttpURLConnection/1.0");
        connection.setRequestProperty("Accept", "application/json");
        
        int responseCode = connection.getResponseCode();
        
        BufferedReader reader;
        if (responseCode >= 200 && responseCode < 300) {
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } else {
            reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        }
        
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line).append("\n");
        }
        reader.close();
        connection.disconnect();
        
        return response.toString();
    }
    
    // Usage example
    public static void main(String[] args) {
        try {
            String result = performGetRequest("https://api.github.com/users/octocat");
            System.out.println("Response: " + result);
        } catch (IOException e) {
            System.err.println("Request failed: " + e.getMessage());
        }
    }
}

Key points in this implementation:

  • Always set reasonable timeouts to prevent hanging connections
  • Check response codes and handle error streams appropriately
  • Set User-Agent header to avoid getting blocked by servers
  • Use try-with-resources or manually close connections to prevent leaks

HTTP POST Request with JSON Payload

POST requests require a bit more setup since you need to write data to the request body. Here's a robust implementation:

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class HttpPostExample {
    
    public static String performPostRequest(String urlString, String jsonPayload) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        
        // Configure for POST
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(10000);
        
        // Set headers
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("User-Agent", "Java-HttpURLConnection/1.0");
        
        // Write request body
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonPayload.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }
        
        // Read response
        int responseCode = connection.getResponseCode();
        InputStream inputStream = responseCode >= 200 && responseCode < 300 
            ? connection.getInputStream() 
            : connection.getErrorStream();
            
        StringBuilder response = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line).append("\n");
            }
        }
        
        connection.disconnect();
        return response.toString();
    }
    
    // Example usage
    public static void main(String[] args) {
        String jsonPayload = "{\"name\":\"John Doe\",\"email\":\"john@example.com\"}";
        
        try {
            String result = performPostRequest("https://httpbin.org/post", jsonPayload);
            System.out.println("Response: " + result);
        } catch (IOException e) {
            System.err.println("POST request failed: " + e.getMessage());
        }
    }
}

Real-World Use Cases and Examples

HttpURLConnection shines in several scenarios where you want to keep dependencies minimal:

Microservice Health Checks: When building distributed systems, you often need lightweight health check mechanisms. HttpURLConnection is perfect for this since it's always available and has a small footprint:

public class HealthChecker {
    public boolean isServiceHealthy(String serviceUrl) {
        try {
            URL url = new URL(serviceUrl + "/health");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(2000);
            connection.setReadTimeout(3000);
            
            int responseCode = connection.getResponseCode();
            connection.disconnect();
            
            return responseCode == 200;
        } catch (Exception e) {
            return false;
        }
    }
}

Webhook Implementations: When your application needs to send webhook notifications, HttpURLConnection provides reliable delivery without external dependencies:

public class WebhookSender {
    public void sendWebhook(String webhookUrl, String eventData) throws IOException {
        URL url = new URL(webhookUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("X-Webhook-Source", "MyApplication");
        
        // Add retry logic for production use
        try (OutputStream os = connection.getOutputStream()) {
            os.write(eventData.getBytes(StandardCharsets.UTF_8));
        }
        
        int responseCode = connection.getResponseCode();
        if (responseCode < 200 || responseCode >= 300) {
            throw new IOException("Webhook delivery failed with code: " + responseCode);
        }
        
        connection.disconnect();
    }
}

Comparison with Alternative HTTP Clients

Feature HttpURLConnection Apache HttpClient OkHttp Java 11 HttpClient
Dependencies None (built-in) External JAR required External JAR required None (Java 11+)
Async Support No Yes Yes Yes
Connection Pooling Basic (automatic) Advanced Advanced Advanced
JSON Support Manual With Jackson/Gson With adapters Manual
Learning Curve Moderate Steep Easy Easy
Performance Good Excellent Excellent Excellent

HttpURLConnection hits the sweet spot when you need simple HTTP operations without bloating your classpath. For complex scenarios with connection pooling, retries, or async operations, consider the alternatives.

Best Practices and Common Pitfalls

Always Set Timeouts: The default timeout values can cause your application to hang indefinitely. Always configure both connect and read timeouts:

connection.setConnectTimeout(5000);  // Connection establishment timeout
connection.setReadTimeout(10000);    // Data read timeout

Handle Response Codes Properly: Don't assume success - always check response codes and handle error streams:

int responseCode = connection.getResponseCode();
InputStream stream = (responseCode >= 200 && responseCode < 300) 
    ? connection.getInputStream() 
    : connection.getErrorStream();

Connection Cleanup: While connection pooling helps, always clean up resources explicitly, especially in high-throughput applications:

// Good practice
try {
    // ... make request
} finally {
    if (connection != null) {
        connection.disconnect();
    }
}

Common Gotchas:

  • Forgetting setDoOutput(true) for POST/PUT requests
  • Not setting Content-Type header for JSON payloads
  • Reading from getInputStream() when response code indicates error
  • Not handling redirects (HttpURLConnection follows redirects by default, but only for GET)
  • Assuming UTF-8 encoding without specifying it explicitly

Security Considerations:

// For HTTPS connections, consider certificate validation
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
// In production, implement proper certificate validation
// httpsConnection.setHostnameVerifier(...);
// httpsConnection.setSSLSocketFactory(...);

Performance Tips:

  • Reuse connections when possible by keeping the connection object alive
  • Set appropriate buffer sizes for large payloads
  • Use system properties to tune connection pooling: http.maxConnections, http.keepAlive
  • Consider chunked encoding for large uploads by setting connection.setChunkedStreamingMode(1024)

For additional details and advanced configuration options, check the official HttpURLConnection documentation which covers all available methods and system properties for fine-tuning behavior.

HttpURLConnection remains a solid choice for straightforward HTTP operations, especially in environments where dependency management is crucial or when you need guaranteed availability across different Java versions. Master these patterns, and you'll have a reliable foundation for most HTTP integration scenarios.



This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.

This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.

Leave a reply

Your email address will not be published. Required fields are marked