Java 中可以使用 Java 标准库中的 HttpURLConnection 类或第三方库如 Apache HttpComponents 来发送 HTTP 请求。

下面是使用 HttpURLConnection 发送 GET 请求的示例代码:

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

public class HttpUrlConnectionExample {

    public static void main(String[] args) {
        try {
            String url = 'https://jsonplaceholder.typicode.com/posts/1';
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod('GET');
            int responseCode = con.getResponseCode();
            System.out.println('Response Code : ' + responseCode);
            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.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

需要注意的是,如果需要发送 POST 请求或其他类型的请求,需要设置请求方法和请求体,具体可以参考 HttpURLConnection 类的 API 文档。

Java 发送 HTTP 请求:使用 HttpURLConnection 和 示例代码

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

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