以下是一个基本的Java程序,用于发送POST请求:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class PostExample {
    public static void main(String[] args) {
        try {
            // 设置POST请求的URL地址和请求参数
            String url = "http://example.com/api";
            String params = "name=" + URLEncoder.encode("张三", "UTF-8") + "&age=" + URLEncoder.encode("25", "UTF-8");

            // 创建连接
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

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

            // 设置请求头信息
            con.setRequestProperty("User-Agent", "Mozilla/5.0");
            con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

            // 启用输出,因为我们要发送数据
            con.setDoOutput(true);

            // 发送请求参数
            con.getOutputStream().write(params.getBytes("UTF-8"));

            // 获取响应状态码
            int responseCode = con.getResponseCode();

            // 读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 输出响应结果
            System.out.println("Response Code : " + responseCode);
            System.out.println("Response Content : " + response.toString());
        } catch (Exception e) {
            System.out.println("Exception : " + e.getMessage());
        }
    }
}

在此示例中,我们使用了HttpURLConnection类来实现POST请求。首先,我们需要设置请求的URL地址和请求参数。然后,我们创建一个URL对象,并使用它来打开连接。接下来,我们设置请求方法为POST,并设置请求头信息。我们启用输出流,并向服务器发送请求参数。然后,我们读取响应状态码和响应内容,并将其存储在一个字符串缓冲区中。最后,我们打印响应结果。

java-jdk18-发送post请求

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

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