在 Java 中,我们通常使用 HttpURLConnection
或第三方库(如 Apache HttpClient
或 OkHttp
)来发送 GET 和 POST 请求。本文将通过示例讲解如何实现这两种 HTTP 请求。
1. 使用 HttpURLConnection
实现 GET 和 POST 请求
HttpURLConnection
是 Java 原生类库中提供的工具,可以用来发送 HTTP 请求。
1.1 GET 请求示例
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;public class GetRequestExample {public static void main(String[] args) {try {// 创建 URL 对象URL url = new URL("https://jsonplaceholder.typicode.com/posts/1");// 打开连接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();}}
}
1.2 POST 请求示例
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;public class PostRequestExample {public static void main(String[] args) {try {// 创建 URL 对象URL url = new URL("https://jsonplaceholder.typicode.com/posts");// 打开连接HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("POST");// 设置请求头connection.setRequestProperty("Content-Type", "application/json; utf-8");connection.setRequestProperty("Accept", "application/json");// 启用写入数据到请求体connection.setDoOutput(true);// JSON 数据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) { // 201BufferedReader 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("POST request failed.");}} catch (Exception e) {e.printStackTrace();}}
}
2. 使用 Apache HttpClient
实现 GET 和 POST 请求
Apache HttpClient
是一个强大的第三方库,适合处理复杂的 HTTP 请求。
2.1 添加 Maven 依赖
在 pom.xml
文件中添加以下依赖:
<dependency><groupId>org.apache.httpcomponents.client5</groupId><artifactId>httpclient5</artifactId><version>5.2</version>
</dependency>
2.2 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.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;import java.io.BufferedReader;
import java.io.InputStreamReader;public class ApacheHttpClientGetExample {public static void main(String[] args) {try (CloseableHttpClient httpClient = HttpClients.createDefault()) {HttpGet request = new HttpGet("https://jsonplaceholder.typicode.com/posts/1");try (CloseableHttpResponse response = httpClient.execute(request)) {System.out.println("Response Code: " + response.getCode());BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));String line;StringBuilder responseContent = new StringBuilder();while ((line = reader.readLine()) != null) {responseContent.append(line);}System.out.println("Response: " + responseContent.toString());}} catch (Exception e) {e.printStackTrace();}}
}
2.3 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.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;import java.io.BufferedReader;
import java.io.InputStreamReader;public class ApacheHttpClientPostExample {public static void main(String[] args) {try (CloseableHttpClient httpClient = HttpClients.createDefault()) {HttpPost post = new HttpPost("https://jsonplaceholder.typicode.com/posts");// 设置请求头post.setHeader("Content-Type", "application/json");// 设置请求体String json = "{ \"title\": \"foo\", \"body\": \"bar\", \"userId\": 1 }";post.setEntity(new StringEntity(json));try (CloseableHttpResponse response = httpClient.execute(post)) {System.out.println("Response Code: " + response.getCode());BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));String line;StringBuilder responseContent = new StringBuilder();while ((line = reader.readLine()) != null) {responseContent.append(line);}System.out.println("Response: " + responseContent.toString());}} catch (Exception e) {e.printStackTrace();}}
}
3. 使用 OkHttp
实现 GET 和 POST 请求
OkHttp
是另一个流行的 HTTP 客户端库,轻量且易用。
3.1 添加 Maven 依赖
在 pom.xml
文件中添加以下依赖:
<dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.11.0</version>
</dependency>
3.2 GET 请求示例
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;public class OkHttpGetExample {public static void main(String[] args) {OkHttpClient client = new OkHttpClient();Request request = new Request.Builder().url("https://jsonplaceholder.typicode.com/posts/1").build();try (Response response = client.newCall(request).execute()) {if (response.isSuccessful()) {System.out.println("Response: " + response.body().string());} else {System.out.println("GET request failed. Code: " + response.code());}} catch (Exception e) {e.printStackTrace();}}
}
3.3 POST 请求示例
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;public class OkHttpPostExample {public static void main(String[] args) {OkHttpClient client = new OkHttpClient();String json = "{ \"title\": \"foo\", \"body\": \"bar\", \"userId\": 1 }";RequestBody body = RequestBody.create(json, MediaType.get("application/json; charset=utf-8"));Request request = new Request.Builder().url("https://jsonplaceholder.typicode.com/posts").post(body).build();try (Response response = client.newCall(request).execute()) {if (response.isSuccessful()) {System.out.println("Response: " + response.body().string());} else {System.out.println("POST request failed. Code: " + response.code());}} catch (Exception e) {e.printStackTrace();}}
}
总结
HttpURLConnection
: 适合简单的 HTTP 请求,原生支持,无需额外依赖。Apache HttpClient
: 功能强大,适合复杂的 HTTP 请求场