Java 发送 POST 请求:详细指南与代码示例
你可以使用 Java 的 HttpURLConnection 类来发送 POST 请求。以下是一个示例代码:
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 PostRequestExample {
public static void main(String[] args) throws IOException {
String url = 'http://192.168.50.150:8080/WebClient/getTimerMusicInfoToDirName?dirName=告警';
String postData = ''; // 如果有POST数据,可以在此处设置
URL requestUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod('POST');
connection.setDoOutput(true);
// 设置POST数据,如果有的话
if (!postData.isEmpty()) {
byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8);
connection.setRequestProperty('Content-Length', String.valueOf(postDataBytes.length));
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
outputStream.write(postDataBytes);
outputStream.flush();
}
}
int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
System.out.println('Response Code: ' + responseCode);
System.out.println('Response Message: ' + responseMessage);
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 Body: ' + response.toString());
}
connection.disconnect();
}
}
你需要将 url 变量设置为你想要发送 POST 请求的 URL。如果有 POST 数据,你可以将其设置为 postData 变量。注意,POST 数据应该以适当的格式传递,例如 JSON 或表单参数。在发送请求后,你可以通过 connection.getResponseCode() 和 connection.getResponseMessage() 获取响应的状态码和消息。响应的主体内容可以通过读取连接的输入流来获取。
原文地址: https://www.cveoy.top/t/topic/o9eS 著作权归作者所有。请勿转载和采集!