調(diào)用天氣 API 獲取實時天氣信息
調(diào)用天氣 API 獲取實時天氣信息
在應(yīng)用中集成天氣信息是一個常見需求,如行程安排、出行提醒等場景。本文將以和風(fēng)天氣(或心知天氣)API 為例,展示如何在 Java 后端調(diào)用第三方天氣 API 并處理返回結(jié)果。
一、注冊天氣服務(wù)平臺賬號
前往和風(fēng)天氣、心知天氣等平臺注冊賬號,申請 API Key。
二、構(gòu)造 API 請求
例如和風(fēng)天氣接口:
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 數(shù)據(jù)
{
"code": "200",
"now": {
"temp": "28",
"text": "晴",
"windDir": "東風(fēng)",
"humidity": "45"
}
}
使用 Jackson 或 Gson 解析數(shù)據(jù):
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(json);
String temp = root.path("now").path("temp").asText();
五、整合至后端服務(wù)
可封裝為 Spring Controller 接口:
@RestController
@RequestMapping("/api/weather")
public class WeatherController {
@GetMapping("/{city}")
public String getWeather(@PathVariable String city) throws Exception {
return WeatherService.getWeather(city);
}
}
六、注意事項
- 需控制請求頻率,避免觸發(fā)平臺限制
- 可使用緩存減少頻繁調(diào)用
- 若城市為中文需轉(zhuǎn)換為城市編碼
通過天氣 API,我們可以為用戶提供更人性化的天氣展示功能。

浙公網(wǎng)安備 33010602011771號