Files
stardew-valley/src/main/java/com/wonderland/stardewvalley/util/WeatherUtil.java
T
2025-10-26 11:31:21 +08:00

69 lines
2.4 KiB
Java

package com.wonderland.stardewvalley.util;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wonderland.stardewvalley.constant.CityCode;
import com.wonderland.stardewvalley.entity.game.Weather;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
@Slf4j
public class WeatherUtil {
/**
* 参考文档: https://lbs.amap.com/api/webservice/guide/api/weatherinfo
* URL 格式: https://restapi.amap.com/v3/weather/weatherInfo?parameters
*
*/
private static final String API_BASE_URL = "https://restapi.amap.com/v3/weather/weatherInfo";
private static final String API_SECRET = "d0f5599ac19a5e4553ba68cd1781d2df";
private static String createUrl() {
StringBuffer stringBuffer = new StringBuffer();
String url = stringBuffer
.append(API_BASE_URL)
.append("?key=")
.append(API_SECRET)
.append("&city=")
.append(CityCode.WuHan.getCode())
.append("&extensions=base")
.toString();
log.info("[Weather] URL: {}", url);
return url;
}
public static Weather getWeather() {
String url = createUrl();
String ans = HttpUtil.get(url);
log.info("[Weather] Response: {}", ans);
// TODO 封装为需要的对象
JSONObject obj = JSONUtil.parseObj(ans);
log.info("[Weather] Obj: {}", obj);
// 检查返回状态码
String status = obj.getStr("status");
if (!"1".equals(status)) {
String info = obj.getStr("info", "Unknown Error");
String errorCode = obj.getStr("infocode", "N/A");
log.error("[Weather] Request failed with code: {}, error: {}", errorCode, info);
return null;
}
// 获取天气信息数组
JSONObject weatherData = obj.getJSONArray("lives").getJSONObject(0);
Weather weather = Weather.builder()
.weather(weatherData.getStr("weather"))
.temperature(weatherData.getStr("temperature"))
.windDirection(weatherData.getStr("winddirection"))
.windPower(weatherData.getStr("windpower"))
.reportTime(weatherData.getStr("reporttime"))
.humidity(weatherData.getStr("humidity"))
.build();
log.info("[Weather] Prepared: {}", weather);
return weather;
}
}