java代码实现http发起post请求
时间: 2023-09-28 17:03:56 浏览: 134
当然,这里是一个Java代码示例,用于发起HTTP POST请求:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPostRequestExample {
public static void main(String[] args) throws Exception {
// 定义POST请求的URL
String url = "http://example.com/api/endpoint";
// 创建URL对象
URL obj = new URL(url);
// 创建HttpURLConnection对象
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
// 设置请求头部信息
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Content-Type", "application/json");
// 设置可写入请求内容
con.setDoOutput(true);
// 构建请求体
String requestBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
// 获取输出流并写入请求体
OutputStream outputStream = con.getOutputStream();
outputStream.write(requestBody.getBytes());
outputStream.flush();
outputStream.close();
// 获取请求响应码
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
// 读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印响应结果
System.out.println("Response : " + response.toString());
}
}
```
请注意,上述代码中的URL和请求头部信息是示例值,你需要根据实际情况进行修改。此外,你还可以根据需要修改请求体内容。
阅读全文