java.net.URLConnection: how to work with HTTP requests and responses

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

Introduction: why URLConnection is a must-know for Java developers

\n\n

Have you ever wondered how your favorite browser or mobile app communicates with a server? The magic lies in simple but powerful HTTP requests. And in Java, there is a "Swiss Army knife" for this — the java.net.URLConnection class.

\n\n

Despite the fact that Java 11 introduced a new modular HttpClient, thousands of developers around the world continue to use the good old URLConnection. Why? First, there is legacy code that needs to be maintained. Second, it is simple and does not require third-party libraries. And third, understanding how HTTP requests work at a low level makes you a true pro.

\n\n

In this article, we won't just copy an answer from Stack Overflow. We will break down two approaches to working with URLConnection and compare them with the modern HttpClient. You will learn how to send GET and POST requests, handle errors, set headers, and read server responses. Let's go!

\n\n

What is java.net.URLConnection and why is it needed?

\n\n

The java.net.URLConnection class is an abstract class that represents an active connection to a resource specified by a URL. In simple terms: it is a bridge between your Java application and a server on the internet. It can:

\n
    \n
  • Open a connection to a server
  • \n
  • Send data (GET, POST, PUT, DELETE)
  • \n
  • Read the server response
  • \n
  • Manage request and response headers
  • \n
  • Work with cookies
  • \n
\n\n

But there is a nuance: URLConnection doesn't do anything by itself. It only provides the mechanism. All the magic is done by its subclasses — for example, HttpURLConnection for working with HTTP.

\n\n

Approach 1: The classic way with HttpURLConnection (time-tested)

\n\n

This method was used by the founding fathers of Java programming. It is reliable but requires manual work. Let's break it down using a GET request as an example.

\n\n

Example 1: GET request with response handling

\n\n
import java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\n\npublic class GetRequestExample {\n    public static void main(String[] args) throws Exception {\n        // 1. Create a URL object\n        URL url = new URL("https://api.github.com/users/octocat");\n        \n        // 2. Open the connection\n        HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n        \n        // 3. Configure the request\n        connection.setRequestMethod("GET");\n        connection.setRequestProperty("User-Agent", "Mozilla/5.0");\n        connection.setConnectTimeout(5000);\n        connection.setReadTimeout(5000);\n        \n        // 4. Check the response code\n        int responseCode = connection.getResponseCode();\n        System.out.println("Response Code: " + responseCode);\n        \n        // 5. Read the response body\n        if (responseCode == HttpURLConnection.HTTP_OK) {\n            BufferedReader in = new BufferedReader(\n                new InputStreamReader(connection.getInputStream()));\n            String inputLine;\n            StringBuilder response = new StringBuilder();\n            \n            while ((inputLine = in.readLine()) != null) {\n                response.append(inputLine);\n            }\n            in.close();\n            \n            System.out.println("Response Body: " + response.toString());\n        } else {\n            System.out.println("GET request failed");\n        }\n        \n        // 6. Close the connection\n        connection.disconnect();\n    }\n}\n
\n\n

Code breakdown:

\n