Comparative Overview of Java HTTP Client Libraries: HttpURLConnection, Apache HttpComponents, Java 9 HttpClient, and OkHttp
This article compares four Java HTTP client options—HttpURLConnection, Apache HttpComponents HttpClient, the Java 9 HttpClient, and OkHttp—detailing their features, code examples, configuration capabilities, and suitability for projects that need connection pooling, DNS control, form/JSON support, and synchronous or asynchronous calls.
The project requires a Java HTTP client library that supports connection‑pool management, DNS resolution control, Form/JSON payloads, and both synchronous and asynchronous calls.
Connection‑pool management (creation, timeout, idle control, per‑host limits).
Custom DNS resolution with load‑balancing and health checks.
Form/JSON request support.
Sync and async invocation.
In the Java ecosystem, HTTP client libraries fall into three broad categories:
JDK’s built‑in HttpURLConnection (low‑level, no connection pool, no HTTP/2).
Apache HttpComponents HttpClient (feature‑rich, widely used, no HTTP/2 in stable releases).
Libraries that rewrite the stack, the most representative being OkHttp (supports HTTP/2, Android‑friendly).
01 HttpURLConnection
Using HttpURLConnection requires manual handling of streams and headers. Example:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUrlConnectionDemo {
public static void main(String[] args) throws Exception {
String urlString = "https://httpbin.org/post";
String bodyString = "password=e10adc3949ba59abbe56e057f20f883e&username=test3";
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(bodyString.getBytes("utf-8"));
os.flush();
os.close();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
System.out.println("rsp:" + sb.toString());
} else {
System.out.println("rsp code:" + conn.getResponseCode());
}
}
}HttpURLConnection is low‑level, lacks connection pooling, DNS control, and does not support HTTP/2.
Java 9 HttpClient
Java 9 introduced a high‑level HttpClient that supports HTTP/2 and provides a fluent API:
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyProcessor.fromString("Sample request body"))
.build();
// send request with HttpClient (omitted for brevity)The API is elegant, but it is only available from Java 9 onward; Java 11 LTS is the first long‑term version that includes it, limiting its use in production today.
02 Apache HttpComponents HttpClient
Apache HttpComponents HttpClient offers extensive features that satisfy all listed requirements, including connection pooling, custom socket and connection configurations, and detailed request/response handling. Example:
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.impl.client.HttpClients;
public class HttpComponentsDemo {
final static CloseableHttpClient client = HttpClients.createDefault();
private String sendPostForm(String url, Map<String, String> params) throws Exception {
HttpPost request = new HttpPost(url);
request.setHeader("X-Http-Demo", HttpComponentsDemo.class.getSimpleName());
if (params != null) {
List<NameValuePair> nameValuePairList = new ArrayList<>();
for (Map.Entry<String, String> entry : params.entrySet()) {
nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
request.setEntity(new UrlEncodedFormEntity(nameValuePairList));
}
CloseableHttpResponse response = client.execute(request);
System.out.println("rsp code:" + response.getStatusLine().getStatusCode());
String ret = readResponseContent(response.getEntity().getContent());
response.close();
return ret;
}
private String readResponseContent(InputStream inputStream) throws Exception {
if (inputStream == null) return "";
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[512];
int len;
while (inputStream.available() > 0) {
len = inputStream.read(buf);
out.write(buf, 0, len);
}
return out.toString();
}
public static void main(String[] args) throws Exception {
HttpComponentsDemo demo = new HttpComponentsDemo();
String url = "https://httpbin.org/post";
Map<String, String> params = new HashMap<>();
params.put("foo", "bar中文");
String rsp = demo.sendPostForm(url, params);
System.out.println("http post rsp:" + rsp);
url = "https://httpbin.org/get";
System.out.println("http get rsp:" + demo.sendGet(url));
}
private String sendGet(String url) throws Exception {
return Request.Get(url)
.connectTimeout(1000)
.socketTimeout(1000)
.execute().returnContent().asString();
}
}Advanced configuration (connection manager, socket config, message constraints, etc.) can be added as shown in the original article.
03 OkHttp
OkHttp provides a friendly API, supports HTTP/2, and includes automatic network recovery, making it the most popular choice for Android apps. Example:
import okhttp3.*;
import org.apache.http.util.CharsetUtils;
import java.util.HashMap;
import java.util.Map;
public class OkHttpDemo {
OkHttpClient client = new OkHttpClient();
private String sendPostForm(String url, final Map<String, String> params) throws Exception {
FormBody.Builder builder = new FormBody.Builder(CharsetUtils.get("UTF-8"));
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.add(entry.getKey(), entry.getValue());
}
}
RequestBody requestBody = builder.build();
Request request = new Request.Builder().url(url).post(requestBody).build();
return client.newCall(request).execute().body().string();
}
private String sendGet(String url) throws Exception {
Request request = new Request.Builder().url(url).build();
return client.newCall(request).execute().body().string();
}
public static void main(String[] args) throws Exception {
OkHttpDemo demo = new OkHttpDemo();
String url = "https://httpbin.org/post";
Map<String, String> params = new HashMap<>();
params.put("foo", "bar中文");
String rsp = demo.sendPostForm(url, params);
System.out.println("http post rsp:" + rsp);
url = "https://httpbin.org/get";
System.out.println("http get rsp:" + demo.sendGet(url));
}
}OkHttp’s design is similar to Java 9’s HttpClient, easing migration for developers who prefer minimal dependencies.
04 Summary
• HttpURLConnection is low‑level and should only be used when avoiding third‑party dependencies is critical. • Java 9+ HttpClient offers a modern API with HTTP/2 but is limited by Java version requirements. • Apache HttpComponents HttpClient is the best choice for server‑side HTTP calls when HTTP/2 is not required. • OkHttp is the preferred library for Android and any client needing HTTP/2 support.
Choose the library that matches your project’s runtime constraints and feature needs.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
