// 示例代码:Java 调用 HTTP 接口
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ApiCaller {
    // 定义一个方法来调用外部接口
    public static void callApi() {
        try {
            // 目标 API 的 URL
            String url = "https://api.example.com/data";
            // 创建 URL 对象
            URL obj = new URL(url);
            // 打开连接
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            // 设置请求方法为 GET
            con.setRequestMethod("GET");
            // 设置请求头(可选)
            con.setRequestProperty("User-Agent", "Mozilla/5.0");
            // 获取响应码
            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());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        // 调用 callApi 方法
        callApi();
    }
}URL 类来表示要访问的 API 地址,并通过 HttpURLConnection 来建立与该 URL 的连接。setRequestMethod("GET") 设置请求类型为 GET 请求。setRequestProperty 方法设置请求头信息,比如 User-Agent。getResponseCode() 获取 HTTP 响应码,并通过 InputStreamReader 和 BufferedReader 读取响应内容。try-catch 块来捕获并处理可能发生的异常。上一篇:java 邮件发送
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站