在Java中发送POST请求,可以使用java.net包中的HttpURLConnection类。以下是一个简单的示例代码:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostRequestExample {
public static void main(String[] args) throws IOException {
String url = "http://example.com/api/endpoint";
String requestBody = "param1=value1¶m2=value2";
// 创建URL对象
URL obj = new URL(url);
// 创建HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 启用输入输出流
connection.setDoInput(true);
connection.setDoOutput(true);
// 设置请求头
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 创建请求体
DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.writeBytes(requestBody);
dataOutputStream.flush();
dataOutputStream.close();
// 获取响应状态码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应内容
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: " + response.toString());
}
}
在上面的示例中,我们首先创建一个URL对象,然后使用该URL对象创建一个HttpURLConnection对象。接下来,我们设置请求方法为POST,并启用输入输出流。然后,我们设置请求头,将请求体写入到输出流中。之后,我们获取响应状态码和响应内容,并打印出来。