import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class HttpPostExample {
public static void main(String[] args) {
try {
// 创建URL对象,指定POST请求的URL
URL url = new URL("https://example.com/api");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 允许发送数据
connection.setDoOutput(true);
// 设置请求头(可选)
connection.setRequestProperty("Content-Type", "application/json");
// 准备要发送的数据
String jsonInputString = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
// 发送POST请求
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 关闭连接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
URL
类创建一个表示目标API地址的对象。openConnection()
方法获取HttpURLConnection
对象,用于与服务器进行通信。setRequestMethod("POST")
指定HTTP请求的方法为POST。setDoOutput(true)
允许向服务器发送数据。Content-Type
等。OutputStream
将数据写入到服务器。getResponseCode()
获取服务器的响应码。上一篇:java多线程executor
下一篇:java二维数组定义方法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站