你可以使用Java中的HttpURLConnection类来发送HTTP 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;

public class HttpPostExample {
    public static void main(String[] args) throws IOException {
        String url = "http://example.com/api/endpoint";
        String postData = "param1=value1&param2=value2";

        // 创建URL对象
        URL obj = new URL(url);
        // 创建HttpURLConnection对象
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求方法为POST
        con.setRequestMethod("POST");
        // 启用输出流
        con.setDoOutput(true);

        // 设置POST数据
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(postData);
        wr.flush();
        wr.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());
    }
}

上面的代码将通过POST方法发送名为"param1"和"param2"的两个参数到指定的URL,并打印出服务器返回的响应结果。你需要将url替换为你要发送请求的URL,并根据需要修改postData中的参数和值

java 发送http post请求

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

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