java中请求post请求的代码
时间: 2024-04-22 12:24:05 浏览: 26
你可以使用 Java 的 HttpURLConnection 类来发送 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) {
String url = "http://example.com/api/endpoint"; // 替换为实际的目标 URL
try {
URL obj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
// 设置请求方法为 POST
connection.setRequestMethod("POST");
// 设置请求头
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
// 设置请求体
String requestBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}"; // 替换为实际的请求体
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(requestBody);
outputStream.flush();
outputStream.close();
// 获取响应状态码
int responseCode = connection.getResponseCode();
// 读取响应内容
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 输出响应结果
System.out.println("Response Code: " + responseCode);
System.out.println("Response Body: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
上述代码使用 HttpURLConnection 类发送 POST 请求,设置请求头、请求体,并获取响应结果。你需要将 `url` 替换为实际的目标 URL,`requestBody` 替换为你想要发送的请求体内容。请注意,此示例中的请求体是 JSON 格式的字符串,如果你需要发送其他类型的数据,请相应地修改请求体的格式。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)