基于api-football数据学习示例
java
import java.net.*;
import java.io.*;
/**
* Football API 学习示例 - 最简版本
*/
public class LearnFootballAPI {
private static final String BASE_URL = "https://v3.football.api-sports.io";
private String apiKey;
public LearnFootballAPI(String apiKey) {
this.apiKey = apiKey;
}
/**
* 发送GET请求
*/
public String get(String path, String query) {
try {
// 1. 构建URL
String urlStr = BASE_URL + path;
if (query != null && !query.isEmpty()) {
urlStr += "?" + query;
}
// 2. 创建连接
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 3. 设置请求头
conn.setRequestMethod("GET");
conn.setRequestProperty("x-rapidapi-key", apiKey);
conn.setRequestProperty("x-rapidapi-host", "v3.football.api-sports.io");
// 4. 获取响应
int code = conn.getResponseCode();
if (code != 200) {
return "Error " + code + ": " + conn.getResponseMessage();
}
// 5. 读取响应数据
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
return response.toString();
} catch (Exception e) {
return "Exception: " + e.getMessage();
}
}
/**
* 示例1: 查询所有国家
*/
public void demoCountries() {
System.out.println("=== 查询所有国家 ===");
String result = get("/countries", "");
System.out.println(result);
}
/**
* 示例2: 查询英超
*/
public void demoPremierLeague() {
System.out.println("\n=== 查询英超 ===");
String result = get("/leagues", "id=39");
System.out.println(result);
}
/**
* 示例3: 查询英超积分榜
*/
public void demoStandings() {
System.out.println("\n=== 查询英超积分榜 ===");
String result = get("/standings", "league=39&season=2023");
System.out.println(result);
}
/**
* 示例4: 查询比赛
*/
public void demoFixtures() {
System.out.println("\n=== 查询今日比赛 ===");
String today = java.time.LocalDate.now().toString();
String result = get("/fixtures", "league=39&season=2023&date=" + today);
System.out.println(result);
}
/**
* 示例5: 查询球员
*/
public void demoPlayers() {
System.out.println("\n=== 查询梅西 ===");
String result = get("/players", "search=messi");
System.out.println(result);
}
/**
* 运行所有示例
*/
public void runAllExamples() {
demoCountries();
demoPremierLeague();
demoStandings();
demoFixtures();
demoPlayers();
}
public static void main(String[] args) {
// 替换为你的API Key
String apiKey = "YOUR_API_KEY_HERE";
LearnFootballAPI api = new LearnFootballAPI(apiKey);
api.runAllExamples();
}
}