调用天气 API 获取实时天气信息

调用天气 API 获取实时天气信息

在应用中集成天气信息是一个常见需求,如行程安排、出行提醒等场景。本文将以和风天气(或心知天气)API 为例,展示如何在 Java 后端调用第三方天气 API 并处理返回结果。

一、注册天气服务平台账号

前往和风天气、心知天气等平台注册账号,申请 API Key。

二、构造 API 请求

例如和风天气接口:

https://devapi.qweather.com/v7/weather/now?location=101010100&key=your_api_key

三、Java 后端请求代码

public class WeatherService {

    public static String getWeather(String location) throws IOException, InterruptedException {
        String apiKey = "your_api_key";
        String url = "https://devapi.qweather.com/v7/weather/now?location=" + location + "&key=" + apiKey;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .GET()
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        return response.body();
    }
}

四、处理返回的 JSON 数据

{
  "code": "200",
  "now": {
    "temp": "28",
    "text": "晴",
    "windDir": "东风",
    "humidity": "45"
  }
}

使用 Jackson 或 Gson 解析数据:

ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(json);
String temp = root.path("now").path("temp").asText();

五、整合至后端服务

可封装为 Spring Controller 接口:

@RestController
@RequestMapping("/api/weather")
public class WeatherController {

    @GetMapping("/{city}")
    public String getWeather(@PathVariable String city) throws Exception {
        return WeatherService.getWeather(city);
    }
}

六、注意事项

  • 需控制请求频率,避免触发平台限制
  • 可使用缓存减少频繁调用
  • 若城市为中文需转换为城市编码

通过天气 API,我们可以为用户提供更人性化的天气展示功能。

posted @ 2025-06-03 20:08  元始天尊123  阅读(17477)  评论(0)    收藏  举报