在 Java 中进行 POST 请求并携带参数有多种实现方式,下面我会详细介绍其中的几种常见方式,并附上相应的示例代码和依赖坐标。
HttpURLConnection
是 Java 标准库提供的类,用于发送 HTTP 请求。以下是步骤流程:
URL
对象,并打开连接。示例代码:
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
public class PostWithHttpURLConnection {
public static void main(String[] args) throws IOException {
String urlString = "https://example.com/api";
String requestBody = "param1=value1¶m2=value2";
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
// 设置请求头,可选
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
try (OutputStream os = connection.getOutputStream()) {
byte[] input = requestBody.getBytes("utf-8");
os.write(input, 0, input.length);
}
int responseCode = connection.getResponseCode();
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println("Response Code: " + responseCode);
System.out.println("Response Body: " + response.toString());
}
}
}
Apache HttpClient 是一个流行的第三方库,简化了 HTTP 请求的处理。以下是步骤流程:
添加 Apache HttpClient 依赖。
Maven 依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
Gradle 依赖:
implementation 'org.apache.httpcomponents:httpclient:4.5.13'
CloseableHttpClient
对象。HttpPost
对象,设置 URL 和请求参数。示例代码:
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class PostWithHttpClient {
public static void main(String[] args) throws IOException {
String urlString = "https://example.com/api";
String requestBody = "param1=value1¶m2=value2";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(urlString);
StringEntity entity = new StringEntity(requestBody);
httpPost.setEntity(entity);
// 设置请求头,可选
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
HttpEntity responseEntity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
try (BufferedReader br = new BufferedReader(new InputStreamReader(responseEntity.getContent()))) {
StringBuilder responseText = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
responseText.append(line);
}
System.out.println("Response Code: " + statusCode);
System.out.println("Response Body: " + responseText.toString());
}
}
}
}
这两种方式都能有效地实现带参数的 POST 请求,具体选择哪种方式取决于你的项目需求和偏好。