Java中 HttpURLConnection 和 HttpClient 详解(初学者友好)
Java中HttpURLConnection
和HttpClient
详解(初学者友好)
在Java开发中,向服务器发送HTTP请求是常见的需求,比如调用API接口或获取远程数据。在JDK中,主要有两种方式实现HTTP通信:
- 使用
HttpURLConnection
(JDK自带)。 - 使用
HttpClient
(JDK 11 引入的新API,推荐方式)。
本文将全面讲解这两种方式,包括基本用法、优缺点以及适用场景。
一、HttpURLConnection
详解
HttpURLConnection
是JDK内置的HTTP请求工具类,无需额外依赖库。它适用于简单的HTTP请求处理。
1. 基本用法
下面是使用 HttpURLConnection
发送 GET 和 POST 请求的示例代码。
(1)GET 请求示例
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;public class HttpURLConnectionGetExample {public static void main(String[] args) {try {String urlString = "https://jsonplaceholder.typicode.com/posts/1";URL url = new URL(urlString);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");// 设置请求头connection.setRequestProperty("User-Agent", "Mozilla/5.0");// 检查响应码int responseCode = connection.getResponseCode();System.out.println("Response Code: " + responseCode);// 读取响应if (responseCode == HttpURLConnection.HTTP_OK) { // 200BufferedReader 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());} else {System.out.println("GET request failed.");}} catch (Exception e) {e.printStackTrace();}}
}
(2)POST 请求示例
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;public class HttpURLConnectionPostExample {public static void main(String[] args) {try {String urlString = "https://jsonplaceholder.typicode.com/posts";URL url = new URL(urlString);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("POST");// 设置请求头connection.setRequestProperty("Content-Type", "application/json; utf-8");connection.setRequestProperty("Accept", "application/json");connection.setDoOutput(true); // 用于设置HTTP请求是否允许向服务器发送数据// 请求体String jsonInputString = "{ \"title\": \"foo\", \"body\": \"bar\", \"userId\": 1 }";// 发送数据try (OutputStream os = connection.getOutputStream()) {byte[] input = jsonInputString.getBytes("utf-8");os.write(input, 0, input.length);}// 检查响应码int responseCode = connection.getResponseCode();System.out.println("Response Code: " + responseCode);if (responseCode == HttpURLConnection.HTTP_CREATED) { // 201System.out.println("POST request successful.");} else {System.out.println("POST request failed.");}} catch (Exception e) {e.printStackTrace();}}
}
2. 优缺点
优点:
- 内置类,无需添加依赖。
- 易于实现简单的HTTP请求。
缺点:
- 使用较复杂,代码冗长。
- 不支持异步。
- 不便于维护和扩展。
二、HttpClient
详解
HttpClient
是 JDK 11 新引入的 HTTP 通信工具,功能强大,支持同步和异步模式。
1. 基本用法
(1)GET 请求示例
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;public class HttpClientGetExample {public static void main(String[] args) {try {HttpClient client = HttpClient.newHttpClient();HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://jsonplaceholder.typicode.com/posts/1")).GET().build();HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());System.out.println("Response Code: " + response.statusCode());System.out.println("Response Body: " + response.body());} catch (Exception e) {e.printStackTrace();}}
}
(2)POST 请求示例
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;public class HttpClientPostExample {public static void main(String[] args) {try {HttpClient client = HttpClient.newHttpClient();String jsonInputString = "{ \"title\": \"foo\", \"body\": \"bar\", \"userId\": 1 }";HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://jsonplaceholder.typicode.com/posts")).header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(jsonInputString)).build();HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());System.out.println("Response Code: " + response.statusCode());System.out.println("Response Body: " + response.body());} catch (Exception e) {e.printStackTrace();}}
}
(3)异步请求示例
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;public class HttpClientAsyncExample {public static void main(String[] args) {HttpClient client = HttpClient.newHttpClient();HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://jsonplaceholder.typicode.com/posts/1")).build();CompletableFuture<HttpResponse<String>> responseFuture = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());responseFuture.thenAccept(response -> {System.out.println("Response Code: " + response.statusCode());System.out.println("Response Body: " + response.body());}).join(); //这里的 .join()是一个阻塞方法,调用这个方法,可以使当前线程(通常是主线程)等待//直到responseFuture完成,避免程序过早退出(单元测试和多异步任务结果合并时常用join方法)}
}
2. 优缺点
优点:
- 简洁且现代化的API。
- 支持同步和异步。
- 支持HTTP/2。
缺点:
- 需要 JDK 11+ 支持。
三、如何选择?
- 简单项目: 如果你的项目无需频繁发送复杂的HTTP请求,
HttpURLConnection
足够。 - 复杂项目: 推荐使用
HttpClient
,它更加现代化、功能全面。
四、总结
HttpURLConnection
和 HttpClient
是 Java 开发中常用的 HTTP 请求工具。对于初学者,建议从简单的 HttpURLConnection
开始掌握基本原理,然后再学习功能更丰富的 HttpClient
。
希望以上内容能够帮助到大家掌握 Java 的 HTTP 请求!欢迎点赞、收藏、评论支持! 😊