httpsurlconnection post
时间: 2023-09-04 19:14:18 浏览: 47
您可以使用以下代码示例来执行基于Java的HTTP POST请求使用HttpURLConnection:
```java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class HttpPostExample {
public static void main(String[] args) throws IOException {
String url = "https://example.com/api/endpoint";
String postData = "param1=value1¶m2=value2";
// 创建URL对象
URL obj = new URL(url);
// 创建HttpURLConnection对象,并进行设置
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 启用输出流,以便将数据写入请求体
con.setDoOutput(true);
// 获取输出流并写入POST数据
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.write(postData.getBytes(StandardCharsets.UTF_8));
}
// 发送请求并获取响应
int responseCode = con.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应内容
try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
// 打印响应内容
System.out.println("Response: " + response.toString());
}
}
}
```
在上述示例中,您需要将`url`替换为您要发送POST请求的URL。`postData`变量是要发送的POST数据,可以根据您的需求进行自定义。然后,通过调用`con.getOutputStream()`获取输出流,并将POST数据写入请求体。最后,通过调用`con.getResponseCode()`获取响应代码,并使用`con.getInputStream()`来获取响应内容。