Java 发送 HTTP POST 请求的方法
使用 HttpURLConnection
(原生 Java 支持)
创建一个 HttpURLConnection
对象,设置请求方法为 POST,并写入请求体数据。以下是一个简单示例:
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPostExample {
public static void main(String[] args) throws Exception {
String url = "https://example.com/api";
String postData = "param1=value1¶m2=value2";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
try (OutputStream os = con.getOutputStream()) {
byte[] input = postData.getBytes("utf-8");
os.write(input, 0, input.length);
}
int responseCode = con.getResponseCode();
System.out.println("Response Code: " + responseCode);
}
}
使用 HttpClient
(Java 11+ 推荐)
HttpClient
是 Java 11 引入的现代化 HTTP 客户端,支持异步和同步请求:
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) throws Exception {
HttpClient client = HttpClient.newHttpClient();
String requestBody = "{\"key\":\"value\"}";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/api"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse<String> response = client.send(
request, HttpResponse.BodyHandlers.ofString()
);
System.out.println(response.body());
}
}
使用第三方库(如 OkHttp
)
OkHttp
是流行的第三方 HTTP 客户端库,简化了请求处理:
import okhttp3.*;
public class OkHttpPostExample {
public static void main(String[] args) throws Exception {
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
String requestBody = "{\"key\":\"value\"}";
Request request = new Request.Builder()
.url("https://example.com/api")
.post(RequestBody.create(requestBody, mediaType))
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response.body().string());
}
}
}
常见参数设置
- 请求头:通过
setRequestProperty
或header()
方法添加,如Content-Type
。 - 超时设置:
HttpURLConnection
使用setConnectTimeout()
,HttpClient
通过Builder
配置。 - 表单数据:格式为
key1=value1&key2=value2
,需设置Content-Type: application/x-www-form-urlencoded
。 - JSON 数据:设置
Content-Type: application/json
,并发送 JSON 字符串。
错误处理
- 检查响应状态码(如 200 表示成功)。
- 捕获
IOException
处理网络异常。 - 使用
try-with-resources
确保资源释放。