**方法 1:使用 java.net.HttpURLConnection(JDK 内置)**
这是 Java 原生的 HTTP 请求方式,无需引入额外依赖。
java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionExample {
public static void main(String[] args) {
try {
// 创建 URL 对象
URL url = new URL("https://api.example.com/data?param1=value1¶m2=value2");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为 GET
connection.setRequestMethod("GET");
// 设置请求头(可选)
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("响应码: " + responseCode);
// 读取响应内容
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream())
);
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 输出响应内容
System.out.println("响应内容: " + response.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
**方法 2:使用 java.net.http.HttpClient(Java 11+)**
Java 11 引入的 HttpClient API,提供了更现代、更易用的 HTTP 客户端。
java
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class HttpClientExample {
public static void main(String[] args) {
// 创建 HttpClient 实例
HttpClient client = HttpClient.newHttpClient();
// 构建 HTTP 请求
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/data?param1=value1¶m2=value2"))
.header("User-Agent", "Java HttpClient")
.build();
// 发送请求并处理响应(同步方式)
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.exceptionally(ex -> {
System.err.println("请求出错: " + ex.getMessage());
return null;
});
// 主线程等待异步请求完成(仅示例需要)
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
**方法 3:使用 Apache HttpClient(第三方库)**
Apache HttpClient 是功能强大的 HTTP 客户端库,需添加 Maven 依赖:
xml
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
java
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class ApacheHttpClientExample {
public static void main(String[] args) {
// 创建 HttpClient 实例
HttpClient client = HttpClients.createDefault();
try {
// 创建 HttpGet 请求
HttpGet request = new HttpGet("https://api.example.com/data?param1=value1¶m2=value2");
// 设置请求头(可选)
request.setHeader("User-Agent", "Apache HttpClient");
// 执行请求
HttpResponse response = client.execute(request);
// 获取响应状态码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("响应码: " + statusCode);
// 获取响应内容
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("响应内容: " + responseBody);
} catch (IOException e) {
e.printStackTrace();
}
}
}
**关键说明:**
1. **URL 参数编码**:
- 如果参数包含特殊字符(如空格、中文),需使用 `URLEncoder` 编码:
```java
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
String paramValue = "特殊字符!";
String encodedValue = URLEncoder.encode(paramValue, StandardCharsets.UTF_8);
String url = "https://api.example.com/data?param=" + encodedValue;
```
2. **异常处理**:
- 网络请求可能抛出 `IOException`,需进行异常处理。
3. **HTTPS 证书验证**:
- 对于自签名证书的 HTTPS 站点,需要配置信任管理器(TrustManager),否则会抛出 `SSLHandshakeException`。
4. **异步请求**:
- Java 11+ 的 HttpClient 支持异步请求(`sendAsync()`),适合高并发场景。
**推荐场景:**
- **简单需求**:使用 `HttpURLConnection`(JDK 内置,无需依赖)。
- **Java 11+**:使用 `java.net.http.HttpClient`(现代 API,支持异步)。
- **复杂场景**:使用 `Apache HttpClient`(功能丰富,支持连接池、重试机制等)。
根据你的项目需求选择合适的实现方式即可。