在 Java 中,常用的发起 HTTP 请求的方式或工具类有以下几种:
1. 原生 Java 方式
(1) HttpURLConnection
-
特点:Java 标准库提供的 HTTP 客户端,无需额外依赖。
-
示例:
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 connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); System.out.println("Response Code: " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println("Response: " + response.toString()); } }
2. 第三方库
(1) OkHttp
-
特点:Square 开源的 HTTP 客户端,性能优异,API 简洁。
-
依赖:
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.10.0</version> </dependency> -
示例:
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("Response Code: " + response.code()); System.out.println("Response Body: " + response.body().string()); } } }
(2) Apache HttpClient
-
特点:Apache 提供的 HTTP 客户端,功能强大,支持高级特性。
-
依赖:
<dependency> <groupId>org.apache.httpcomponents.client5</groupId> <artifactId>httpclient5</artifactId> <version>5.1.3</version> </dependency> -
示例:
import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.classic.methods.CloseableHttpResponse; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.io.entity.EntityUtils; public class HttpClientExample { public static void main(String[] args) throws Exception { try (CloseableHttpClient client = HttpClients.createDefault()) { HttpGet request = new HttpGet("https://jsonplaceholder.typicode.com/posts/1"); try (CloseableHttpResponse response = client.execute(request)) { System.out.println("Response Code: " + response.getCode()); System.out.println("Response Body: " + EntityUtils.toString(response.getEntity())); } } } }
(3) Spring RestTemplate
-
特点:Spring 提供的 HTTP 客户端,集成 Spring 生态,适合 Spring 项目。
-
依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> -
示例:
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); } }
(4) Spring WebClient
-
特点:Spring 5 引入的响应式 HTTP 客户端,支持异步和非阻塞。
-
依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> -
示例:
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); System.out.println("Response: " + response.block()); } }
3. 工具类封装
(1) 基于 OkHttp 的工具类
import okhttp3.*;
import java.io.IOException;
public class OkHttpUtils {
private static final OkHttpClient client = new OkHttpClient();
public static String get(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code: " + response.code());
}
return response.body().string();
}
}
public static String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(json, MediaType.parse("application/json"));
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code: " + response.code());
}
return response.body().string();
}
}
}
(2) 基于 RestTemplate 的工具类
import org.springframework.web.client.RestTemplate;
public class RestTemplateUtils {
private static final RestTemplate restTemplate = new RestTemplate();
public static String get(String url) {
return restTemplate.getForObject(url, String.class);
}
public static String post(String url, Object request) {
return restTemplate.postForObject(url, request, String.class);
}
}
4. 对比与选择
| 工具/库 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
| HttpURLConnection | 无需额外依赖,适合简单场景 | API 繁琐,功能有限 | 简单 HTTP 请求 |
| OkHttp | 性能优异,API 简洁 | 需要额外依赖 | 高性能 HTTP 请求 |
| Apache HttpClient | 功能强大,支持高级特性 | API 复杂,依赖较多 | 复杂 HTTP 请求 |
| RestTemplate | 集成 Spring 生态,API 简单 | 同步阻塞,不支持响应式编程 | Spring 项目中的 HTTP 请求 |
| WebClient | 支持响应式编程,异步非阻塞 | 需要学习响应式编程 | Spring 5+ 项目中的 HTTP 请求 |
总结
-
推荐工具:
- 如果需要高性能和简洁 API,选择 OkHttp。
- 如果是 Spring 项目,选择 RestTemplate 或 WebClient。
- 如果需要高级功能,选择 Apache HttpClient。
-
工具类封装:根据项目需求封装工具类,提高代码复用性。