目录
一、API 调用的基本概念
API(Application Programming Interface)是应用程序之间的通信桥梁,允许开发者通过 HTTP 请求获取数据或执行操作。在 Java 中,API 调用通常涉及发送 HTTP 请求并处理响应。以下是几种常见的 API 调用方式及其代码示例。
二、使用 HttpURLConnection
调用 API
HttpURLConnection
是 Java 自带的类,适用于简单的 HTTP 请求和响应处理。
(一)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 {
URL url = new URL("https://api.example.com/data");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.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) <