How to Handle HTTP Requests in Java with Ease

SwiftProxy
By - Emily Chan
2025-07-31 15:45:05

How to Handle HTTP Requests in Java with Ease

The internet operates entirely on requests. This isn't just a saying—it's a fact. Every webpage accessed or API called relies on an HTTP request working behind the scenes. Java is one of the most powerful tools for handling these requests.
If you're building anything that communicates over the web—from scraping data to integrating with APIs—knowing how to send HTTP requests in Java is non-negotiable. So, let's dive in and get you writing powerful HTTP calls that actually work.

Getting Your Java Environment Ready

Before we jump into code, make sure you’ve got the Java Development Kit (JDK) installed. No guesswork here—grab the official installer from the Java downloads page and follow the setup.
Once done, choose your preferred code editor. VS Code is a great option for its lightweight design and easy terminal integration, while IDEs like IntelliJ also provide robust features.
Create a new folder, toss in a file named Main.java, and open your terminal there.
Let's start simple — pop in this classic first program:

class Main {
    public static void main(String[] args){
        System.out.println("Hello world!");
    }
}

Run these commands:

javac Main.java
java Main

If you see Hello world! printed, you're good to go.

Picking the Right HTTP Client in Java

Java offers a few options for HTTP clients. The old faithful was HttpURLConnection. Reliable? Yes. Elegant? Not so much. It's bulky and verbose.
The new kid on the block, introduced in Java 11, is java.net.http.HttpClient. Sleek, modern, and efficient. Plus, you don't have to add any external libraries.
For production-ready projects, libraries like Apache HttpClient or OkHttp are popular, but today, let's keep it simple and stick to the built-in HttpClient.
Here's how to start setting it up:

import java.net.http.HttpClient;

class Main {
    public static void main(String[] args){
        String url = "https://ip.example.com/";
        HttpClient client = HttpClient.newHttpClient();
    }
}

Sending Your First GET Request

GET requests are straightforward—they fetch data. To build the request, import a few more classes:

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

Now the code to send the GET request and print the response:

class Main {
    public static void main(String[] args){
        String url = "https://ip.example.com/";
        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .GET()
            .build();

        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            System.out.println("Status code: " + response.statusCode());
            System.out.println("Response body: " + response.body());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Run it. If all goes well, you’ll get:

Status code: 200
Response body: <your_ip_address>

Boom. You just sent your first HTTP GET request in Java.

Sending a POST Request with a JSON Body

GET is for fetching data. POST is for sending it.
Imagine you want to send a JSON payload. Java doesn't have built-in JSON serialization, so you’d usually use libraries like Jackson or Gson. For this demo, we’ll build a tiny helper method to convert a Map<String, String> to a JSON string.

private static String mapToJson(Map<String, String> data) {
    StringBuilder jsonBuilder = new StringBuilder("{");
    boolean first = true;
    for (Map.Entry<String, String> entry : data.entrySet()) {
        if (!first) jsonBuilder.append(",");
        jsonBuilder.append("\"").append(entry.getKey()).append("\":\"").append(entry.getValue()).append("\"");
        first = false;
    }
    jsonBuilder.append("}");
    return jsonBuilder.toString();
}

Now let's create a POST request that sends some user data to httpbin.org, a testing endpoint:

import java.net.URI;
import java.net.http.*;
import java.util.HashMap;
import java.util.Map;

class Main {

    private static String mapToJson(Map<String, String> data) {
        StringBuilder jsonBuilder = new StringBuilder("{");
        boolean first = true;
        for (Map.Entry<String, String> entry : data.entrySet()) {
            if (!first) jsonBuilder.append(",");
            jsonBuilder.append("\"").append(entry.getKey()).append("\":\"").append(entry.getValue()).append("\"");
            first = false;
        }
        jsonBuilder.append("}");
        return jsonBuilder.toString();
    }

    public static void main(String[] args){
        String url = "https://httpbin.org/post";

        Map<String, String> data = new HashMap<>();
        data.put("username", "testuser");
        data.put("email", "[email protected]");

        String jsonBody = mapToJson(data);

        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
            .build();

        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            System.out.println("Status code: " + response.statusCode());
            System.out.println("Response body: " + response.body());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Run this, and the server echoes your JSON back. You’ve mastered POST requests.

Adding Custom Headers

Headers carry essential info—authentication tokens, content types, caching rules, and more.
Want to tell the server your request body is JSON? Easy:

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create(url))
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
    .build();

Headers are just key-value pairs. Need an API key? Add another .header() call.

Sending Requests Through a Proxy

Sometimes, you want your request to wear a mask—a proxy server. Whether to route traffic, bypass geoblocks, or anonymize scraping, proxies are essential tools.
Java makes it straightforward:

import java.net.InetSocketAddress;
import java.net.ProxySelector;

InetSocketAddress proxyAddress = new InetSocketAddress("pr.example.com", 10000);
ProxySelector proxySelector = ProxySelector.of(proxyAddress);

HttpClient client = HttpClient.newBuilder()
    .proxy(proxySelector)
    .build();

Make sure your IP is whitelisted in the proxy provider's dashboard.
Send your requests as usual, and voilà — your traffic routes through the proxy IP.

Wrapping Up

With these fundamentals, you're equipped to work with HTTP requests in Java—from basic GET and POST requests with JSON, to adding custom headers and using proxies. Whether you're scraping data, integrating APIs, or building web clients, this knowledge will serve you well. Keep practicing, and you'll be able to handle more complex network tasks with confidence.

Note sur l'auteur

SwiftProxy
Emily Chan
Rédactrice en chef chez Swiftproxy
Emily Chan est la rédactrice en chef chez Swiftproxy, avec plus de dix ans d'expérience dans la technologie, les infrastructures numériques et la communication stratégique. Basée à Hong Kong, elle combine une connaissance régionale approfondie avec une voix claire et pratique pour aider les entreprises à naviguer dans le monde en évolution des solutions proxy et de la croissance basée sur les données.
Le contenu fourni sur le blog Swiftproxy est destiné uniquement à des fins d'information et est présenté sans aucune garantie. Swiftproxy ne garantit pas l'exactitude, l'exhaustivité ou la conformité légale des informations contenues, ni n'assume de responsabilité pour le contenu des sites tiers référencés dans le blog. Avant d'engager toute activité de scraping web ou de collecte automatisée de données, il est fortement conseillé aux lecteurs de consulter un conseiller juridique qualifié et de revoir les conditions d'utilisation applicables du site cible. Dans certains cas, une autorisation explicite ou un permis de scraping peut être requis.
SwiftProxy SwiftProxy SwiftProxy
SwiftProxy