要发送POST请求,可以使用Java的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;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HttpPostExample {

    public static void main(String[] args) throws IOException {
        String url = 'http://192.168.50.150:8080/WebClient/getTimerMusicInfoToDirName?dirName=告警';
        String postData = ''; // 如果有参数,可以在这里设置POST请求的参数

        String response = sendPostRequest(url, postData);
        System.out.println(response);
    }

    public static String sendPostRequest(String url, String postData) throws IOException {
        URL requestUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setRequestMethod('POST');
        connection.setDoOutput(true);

        if (postData != null && !postData.isEmpty()) {
            byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8);
            connection.setRequestProperty('Content-Length', String.valueOf(postDataBytes.length));
            try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
                wr.write(postDataBytes);
            }
        }

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = in.readLine()) != null) {
                    response.append(line);
                }
                return response.toString();
            }
        } else {
            throw new IOException('POST request failed with response code: ' + responseCode);
        }
    }
}

你需要将上述代码中的url替换为你要发送POST请求的URL,如果有参数需要传递,可以在postData中设置。然后,调用sendPostRequest方法即可发送POST请求并获取响应。

Java发送POST请求 - HttpURLConnection示例

原文地址: https://www.cveoy.top/t/topic/o9e0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录