RESTful API Calls in Java: From Basic to Advanced Implementations

Nov 09, 2025 · Programming · 17 views · 7.8

Keywords: Java | RESTful API | HttpURLConnection | Apache HttpClient | HTTP Requests

Abstract: This article provides an in-depth exploration of various approaches to implement RESTful API calls in Java, with detailed comparisons between native Java APIs and third-party libraries. It covers core technologies including HttpURLConnection and Apache HttpClient, presents complete code examples for HTTP methods like GET, POST, PUT, DELETE, and offers practical advice on error handling and performance optimization.

Fundamental Concepts of RESTful API Calls

In the Java ecosystem, RESTful API calls typically refer to communication with web services through the HTTP protocol. While the REST architectural style encompasses complex concepts like resources and state transfer, in practical development scenarios, developers primarily focus on sending HTTP requests and processing responses. Java offers multiple approaches to achieve this functionality, ranging from native java.net packages to feature-rich third-party libraries.

Native Java Implementation Approaches

The Java Standard Library provides basic HTTP communication capabilities through java.net.HttpURLConnection and javax.net.ssl.HttpsURLConnection. These classes are encapsulated within a factory pattern and accessed uniformly via URLConnection. When using native APIs, developers need to manually handle various aspects including connection establishment, request transmission, and response reception.

GET Request Implementation Example

Below is a complete example demonstrating GET request implementation using HttpURLConnection:

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

public class RestClient {
    public static String sendGetRequest(String urlString) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/json");
        
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            return response.toString();
        } else {
            throw new RuntimeException("HTTP GET Request Failed with Error code : " + responseCode);
        }
    }
}

POST Request Implementation Example

POST requests requiring data transmission involve more complex implementation:

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class RestClient {
    public static String sendPostRequest(String urlString, String jsonInput) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setDoOutput(true);
        
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonInput.getBytes("utf-8");
            os.write(input, 0, input.length);
        }
        
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_OK) {
            // Process successful response
            return readResponse(connection);
        } else {
            throw new RuntimeException("HTTP POST Request Failed with Error code : " + responseCode);
        }
    }
    
    private static String readResponse(HttpURLConnection connection) throws Exception {
        // Response reading logic
        return "Response content";
    }
}

Apache HttpClient Alternative

Apache HttpClient offers more stable and powerful HTTP protocol support compared to native APIs. The latest version (HttpClient 4) supports complete HTTP protocol stack, including strict mode configuration. Compared to native APIs, HttpClient provides cleaner APIs and better error handling mechanisms.

HttpClient GET Request Example

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClientExample {
    public static String executeGetRequest(String url) throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet request = new HttpGet(url);
            request.addHeader("Accept", "application/json");
            
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                return EntityUtils.toString(response.getEntity());
            }
        }
    }
}

Response Handling and Error Management

Regardless of the implementation approach chosen, proper response handling and error management are crucial. Developers need to check HTTP status codes, handle different response scenarios, and properly manage connection resources. For JSON responses, libraries like Jackson or Gson are typically required for parsing.

Performance and Best Practices

In production environments, using connection pools to manage HTTP connections is recommended to avoid the overhead of frequent connection creation and destruction. For high-concurrency scenarios, Apache HttpClient provides superior connection management capabilities. Additionally, setting appropriate timeout values and implementing retry mechanisms are essential for ensuring system stability.

Framework Selection Recommendations

While native APIs and Apache HttpClient can meet basic requirements, in complex microservices architectures, Spring Framework's RestTemplate or WebClient offer higher-level abstractions and integration capabilities. The choice of approach should consider project complexity, team familiarity, and performance requirements.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.