酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

Java 原生代码实现 POST 请求:向请求体添加参数示例

以下是一个使用 Java 原生代码发送 `POST` 请求并向请求体中添加参数的示例: ```java import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class PostRequestExample { public static void main(String[] args) { try { // 要请求的 URL URL url = new URL("http://your-target-url"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法为 POST connection.setRequestMethod("POST"); // 允许输出 connection.setDoOutput(true); // 设置请求头 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 准备数据 String params = "param1=value1&param2=value2"; // 向输出流写入数据 try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { outputStream.writeBytes(params); outputStream.flush(); } // 获取响应 int responseCode = connection.getResponseCode(); System.out.println("Response Code: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK) { // 读取响应内容 try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine())!= null) { response.append(line); } System.out.println("Response: " + response.toString()); } } else { System.out.println("Request failed"); } } catch (Exception e) { e.printStackTrace(); } } } ``` 在上述示例中,您需要将 `http://your-target-url` 替换为您实际要发送请求的目标 URL,并根据需要修改参数 `param1` 和 `value1` 等。 ######[AI写代码神器 | 453点数解答 | 2024-11-09 12:22:52]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]