以下是Java中发送POST请求的示例代码:

import java.net.*;
import java.io.*;

public class PostRequest {

    public static void main(String[] args) throws Exception {

        // 设置请求的URL
        URL url = new URL("http://example.com/api");

        // 创建连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type","application/json");
        conn.setDoOutput(true);

        // 设置请求体
        String requestData = "{\"name\":\"John\", \"age\":30}";
        OutputStream os = conn.getOutputStream();
        os.write(requestData.getBytes());
        os.flush();
        os.close();

        // 获取响应码
        int responseCode = conn.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        // 获取响应内容
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 打印响应内容
        System.out.println("Response Body: " + response.toString());
    }
}

在这个示例中,我们使用了java.net.HttpURLConnection类来创建POST请求,并设置请求体为一个JSON字符串。我们还设置了Content-Type请求头来指定请求体的数据类型。最后,我们获取响应码和响应内容,并将其打印出来。请注意,在实际使用中,您需要根据具体情况进行修改。


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

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