Backend Development 8 min read

Various Ways to Send HTTP Requests in Java

This article introduces multiple Java approaches for sending HTTP GET and POST requests, covering the built‑in HttpURLConnection class, Apache HttpClient, Square's OkHttp, and Spring's RestTemplate, with step‑by‑step explanations and complete code examples for each method.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
Various Ways to Send HTTP Requests in Java

In daily development, sending HTTP requests is common; this article uses Java to summarize several ways to perform HTTP GET and POST operations.

GET Process

Create a remote connection

Set the request method (GET, POST, PUT…)

Configure connection timeout

Configure read timeout

Send the request

Read the response data

Close the connection

POST Process

Create a remote connection

Set the request method (GET, POST, PUT…)

Configure connection timeout

Configure read timeout

Enable output with setDoOutput(true) when sending data

Optionally enable input with setDoInput(true)

Set request headers via setRequestProperty

Provide authentication header (e.g., Authorization )

Set request parameters

Send the request

Read the response data

Close the connection

1. Using HttpURLConnection

The HttpURLConnection class from the Java standard library allows low‑level control of HTTP communication. Common methods include setRequestMethod() , setRequestProperty() , and getResponseCode() .

import java.net.*;
import java.io.*;

public class HttpURLConnectionExample {
    private static HttpURLConnection con;
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://www.example.com");
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer content = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();
        con.disconnect();
        System.out.println(content.toString());
    }
}

2. Using Apache HttpClient

Apache HttpClient provides a higher‑level API with support for connection pooling and easier header/parameter handling.

import org.apache.http.HttpEntity;
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 void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet("https://www.example.com");
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
            System.out.println(result);
        } finally {
            response.close();
        }
    }
}

3. Using OkHttp

OkHttp, developed by Square, is a lightweight HTTP client that works well with Retrofit and supports HTTP/1.1 and SPDY.

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;

public class OkhttpExample {
    private static final OkHttpClient client = new OkHttpClient();
    public static void main(String[] args) throws IOException {
        Request request = new Request.Builder()
            .url("https://www.example.com")
            .build();
        try (Response response = client.newCall(request).execute()) {
            String result = response.body().string();
            System.out.println(result);
        }
    }
}

4. Using Spring RestTemplate

The Spring RestTemplate simplifies RESTful calls by handling serialization and HTTP method selection.

public class HttpTemplate {
    public static String httpGet(String url) {
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.exchange(url, HttpMethod.GET, null, String.class).getBody();
    }
    public static String httpPost(String url, String name) {
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.postForEntity(url, name, String.class).getBody();
    }
    public static void main(String[] str) {
        System.out.println(HttpTemplate.httpGet("https://www.example.com"));
        System.out.println(HttpTemplate.httpPost("https://www.example.com", "ming"));
    }
}

Note: The examples omit error handling; in production code you should catch and process exceptions appropriately.

Conclusion

The article briefly presents four common Java techniques for sending HTTP requests; developers can choose the most suitable one based on project requirements.

BackendJavaHTTPRestTemplateOkHttpHttpClienthttpurlconnection
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.