import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class JsonPostExample {
public static void main(String[] args) {
try {
// 定义请求的URL
URL url = new URL("https://example.com/api/endpoint");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
conn.setRequestMethod("POST");
// 设置请求头,指定Content-Type为application/json
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty("Accept", "application/json");
// 允许发送数据
conn.setDoOutput(true);
// JSON格式的请求体
String jsonInputString = "{\"key1\": \"value1\", \"key2\": \"value2\"}";
// 发送请求体
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// 获取响应码
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 关闭连接
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
HttpURLConnection对象来打开连接。Content-Type为application/json,表示请求体是JSON格式的数据。OutputStream将字节写入连接。getResponseCode()方法获取HTTP响应码,以确认请求是否成功。如果需要更复杂的处理(如读取响应内容、处理异常等),可以根据需求进一步扩展代码。
上一篇:string在java中代表什么
下一篇:java引用数据类型有哪些
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站