在 Java 开发中,HTTP 客户端是与 RESTful API 交互的核心工具。以下是 Java 中常见的 HTTP 客户端库及其使用示例,涵盖不同场景和需求。


1. HttpURLConnection(Java 原生)

  • 特点:无需额外依赖,但配置繁琐。
  • 适用场景:简单需求或轻量级项目。

示例:GET 请求

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUrlConnectionExample {
public static void main(String[] args) throws Exception {
URL url = new URL("https://jsonplaceholder.typicode.com/posts/1");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");

int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

System.out.println("Response Body: " + response.toString());
}
}

示例:POST 请求

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUrlConnectionPostExample {
public static void main(String[] args) throws Exception {
URL url = new URL("https://jsonplaceholder.typicode.com/posts");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setDoOutput(true);

String jsonInputString = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";

try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}

int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
}
}

2. Apache HttpClient

  • 特点:功能强大,支持连接池、重试机制。
  • 依赖
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2.1</version>
</dependency>

示例:GET 请求

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.io.entity.EntityUtils;

public class ApacheHttpClientExample {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet request = new HttpGet("https://jsonplaceholder.typicode.com/posts/1");

ClassicHttpResponse response = httpClient.execute(request);
System.out.println("Status Code: " + response.getCode());
System.out.println("Response Body: " + EntityUtils.toString(response.getEntity()));
httpClient.close();
}
}

示例:POST 请求

import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.StringEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.io.entity.EntityUtils;

public class ApacheHttpClientPostExample {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost request = new HttpPost("https://jsonplaceholder.typicode.com/posts");

String json = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
request.setEntity(new StringEntity(json, "UTF-8"));
request.setHeader("Content-Type", "application/json");

ClassicHttpResponse response = httpClient.execute(request);
System.out.println("Status Code: " + response.getCode());
System.out.println("Response Body: " + EntityUtils.toString(response.getEntity()));
httpClient.close();
}
}

3. OkHttp

  • 特点:轻量、高效,支持异步请求和自动 GZIP。
  • 依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>

示例:同步 GET 请求

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpExample {
public static void main(String[] args) throws Exception {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://jsonplaceholder.typicode.com/posts/1")
.build();

try (Response response = client.newCall(request).execute()) {
System.out.println("Status Code: " + response.code());
System.out.println("Response Body: " + response.body().string());
}
}
}

示例:异步 POST 请求

import okhttp3.*;

import java.io.IOException;

public class OkHttpPostAsyncExample {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.get("application/json; charset=utf-8");
String json = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder()
.url("https://jsonplaceholder.typicode.com/posts")
.post(body)
.build();

client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}

@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println("Status Code: " + response.code());
System.out.println("Response Body: " + response.body().string());
}
});
}
}

4. Spring RestTemplate(已过时)

  • 特点:Spring 框架内建,适合阻塞式请求。
  • 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

示例:GET 请求

import org.springframework.web.client.RestTemplate;

public class RestTemplateExample {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
String url = "https://jsonplaceholder.typicode.com/posts/1";
String response = restTemplate.getForObject(url, String.class);
System.out.println("Response: " + response);
}
}

5. Spring WebClient(推荐)

  • 特点:非阻塞、响应式编程,适合 Spring WebFlux。
  • 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

示例:同步 GET 请求

import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

public class WebClientExample {
public static void main(String[] args) {
WebClient client = WebClient.create();
Mono<String> response = client.get()
.uri("https://jsonplaceholder.typicode.com/posts/1")
.retrieve()
.bodyToMono(String.class);

String result = response.block();
System.out.println("Response: " + result);
}
}

6. Java 11 HttpClient(现代标准)

  • 特点:Java 11+ 原生支持,支持同步和异步。
  • 示例:GET 请求
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Java11HttpClientExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
.build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
}
}

总结对比

客户端 优点 缺点 适用场景
HttpURLConnection 无需依赖 配置繁琐 简单需求
Apache HttpClient 功能强大,支持连接池 依赖多,配置复杂 企业级应用
OkHttp 轻量、高效,支持异步 需要额外依赖 Android/移动开发
RestTemplate Spring 内建 已过时,不支持异步 旧版 Spring 项目
WebClient 非阻塞、响应式 需要 Spring WebFlux 支持 响应式编程
Java 11 HttpClient 标准 API,支持异步 Java 11+ 才能使用 现代 Java 项目

根据项目需求选择合适的 HTTP 客户端:

  • 简单需求HttpURLConnectionJava 11 HttpClient
  • 企业级应用Apache HttpClient
  • 移动开发OkHttp
  • Spring 项目WebClient(推荐)

更多推荐