HTTP Client in Java: Making Requests the Right Way

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

HTTP client in Java: making requests correctly



In modern development, almost any application interacts with external services via HTTP. Whether it's a REST API, downloading data from a server, or submitting forms — the ability to work with HTTP requests is a mandatory skill for a Java developer. In this article, we will look at how to create an HTTP client in Java, using both standard tools and popular third-party libraries. You will learn how to correctly perform GET and POST requests, handle errors, and parse responses.



1. Classic approach: HttpURLConnection



For a long time, the standard way to work with HTTP in Java was the HttpURLConnection class. It is part of the java.net package and does not require installing additional dependencies. Let's look at an example of performing a GET request:



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

public class SimpleHttpClient { public static void main(String[] args) throws Exception { URL url = new URL("https://api.example.com/data"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json");

int responseCode = connection.getResponseCode(); System.out.println("Response Code: " + responseCode);

if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println("Response: " + response.toString()); } else { System.out.println("GET request failed"); } connection.disconnect(); }}


For a POST request with JSON data transfer, the code will be slightly more complex:



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

public class PostExample { public static void main(String[] args) throws Exception { URL url = new URL("https://api.example.com/users"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true);

String jsonInput = "{\\"name\\":\\"John\\",\\"email\\":\\"john@example.com\\"}";

try (OutputStream os = connection.getOutputStream()) { byte[] input = jsonInput.getBytes("utf-8"); os.write(input, 0, input.length); }

int responseCode = connection.getResponseCode(); System.out.println("POST Response Code: " + responseCode);

if (responseCode == HttpURLConnection.HTTP_CREATED) { // Reading the response is similar to GET } connection.disconnect(); }}


Advantages of HttpURLConnection:

  • Does not require additional libraries
  • Full control over the request
  • Support for all HTTP methods


Disadvantages:

  • Verbose and inconvenient API
  • Difficult to handle errors
  • No built-in support for modern protocols (HTTP/2)


2. Modern standard: HttpClient (Java 11+)



Starting from Java 11, a new java.net.http.HttpClient was added to the standard library. It provides a modern, asynchronous, and much more convenient API. Here's what a GET request looks like using it:



import java.net.URI;import java.net.http.HttpClient;import java.net.ht                

Blogs

Book Recommendations