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.

關於作者

SwiftProxy
Emily Chan
Swiftproxy首席撰稿人
Emily Chan是Swiftproxy的首席撰稿人,擁有十多年技術、數字基礎設施和戰略傳播的經驗。她常駐香港,結合區域洞察力和清晰實用的表達,幫助企業駕馭不斷變化的代理IP解決方案和數據驅動增長。
Swiftproxy部落格提供的內容僅供參考,不提供任何形式的保證。Swiftproxy不保證所含資訊的準確性、完整性或合法合規性,也不對部落格中引用的第三方網站內容承擔任何責任。讀者在進行任何網頁抓取或自動化資料蒐集活動之前,強烈建議諮詢合格的法律顧問,並仔細閱讀目標網站的服務條款。在某些情況下,可能需要明確授權或抓取許可。
SwiftProxy SwiftProxy SwiftProxy
SwiftProxy