(一)注册API Token
https://www.ncdc.noaa.gov/cdo-web/token
(二)调用API查询气象站
public static final String BASE_URL = "https://www.ncdc.noaa.gov/cdo-web/api/v2";
public static final String API_TOKEN = "自己的apikey";
public static void main(String[] args) throws Exception {
double lat = 34.2050708;
double lon = 117.2782967;
String url = BASE_URL + "/stations?" +
"extent=" + (lat - 0.5) + "," + (lon - 0.5) + "," + (lat + 0.5) + "," + (lon + 0.5) + // 近似范围
"&datasetid=GHCND" + // 全球历史气候网络数据集
"&limit=" + 5;
HttpGet request = new HttpGet(url);
request.addHeader("token", API_TOKEN11);
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(request)) {
checkResponse(response);
String json = EntityUtils.toString(response.getEntity());
JsonNode root = mapper.readTree(json);
JsonNode stations = root.get("results");
List<String> ids = new ArrayList<>();
for (JsonNode station : stations) {
ids.add(station.get("id").asText());
if (ids.size() >= 5) break;
}
System.out.println("获取的气象站id"+ids);
}
}
private static void checkResponse(CloseableHttpResponse response) throws IOException {
// 1. 获取 HTTP 状态码
int status = response.getStatusLine().getStatusCode();
// 2. 如果状态码不是 200,抛出异常
if (status != 200) {
// 3. 提取响应体内容(错误详情)
String errorBody = EntityUtils.toString(response.getEntity());
// 4. 构造异常信息
throw new IOException("API请求失败: HTTP " + status
+ "\n响应内容: " + errorBody);
}
}
注意事项
-
API限制:NOAA API每小时最多允许1000次请求