首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

与curl调用等效的Java HTTP POST请求代码

可以使用Java的HttpURLConnection类来实现。下面是一个示例代码:

代码语言:txt
复制
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

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

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

        // 设置请求方法为POST
        con.setRequestMethod("POST");

        // 启用输出流
        con.setDoOutput(true);

        // 设置请求头信息
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        // 获取输出流对象
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        // 发送POST请求参数
        wr.writeBytes(data);
        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());
    }
}

这段代码使用HttpURLConnection发送了一个POST请求,并读取了响应内容。你可以将url替换为你要发送请求的URL,将data替换为你要发送的POST参数。在实际使用中,你可能还需要处理异常、设置请求头、处理响应等其他操作。

这是一个基本的Java HTTP POST请求代码示例,你可以根据具体需求进行修改和扩展。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券