接入接口前首先申请应用密钥Key,登录高德开发者开放平台,创建应用,获取密钥。
天气查询API服务地址:https://restapi.amap.com/v3/weather/weatherInfo?parameters,需以Get请求方式调用,parameters代表所有参数,参数以&进行分隔。
前两个参数为必填参数,extensions传入base代表实况天气,all代表预报天气,定义枚举用以区分:
publicenumGetDataType{ /// <summary>/// 获取实况天气/// </summary>Lives, /// <summary>/// 获取预报天气/// </summary>Forecast}
这里我们以JSON格式解析接口响应数据,所以output传入JSON。最终封装Weather天气类:
usingSystem; usingUnityEngine; usingSystem.Collections; usingUnityEngine.Networking; [AddComponentMenu("")] publicclassWeather : MonoBehaviour{ privatestaticWeatherinstance; publicstaticWeatherInstance { get { if (instance==null) { instance=newGameObject("[Weather]").AddComponent<Weather>(); DontDestroyOnLoad(instance); } returninstance; } } //密钥 于高德开发者平台创建应用申请获得privateconststringkey=""; publicenumGetDataType { /// <summary>/// 获取实况天气/// </summary>Lives, /// <summary>/// 获取预报天气/// </summary>Forecast } /// <summary>/// 获取天气数据/// </summary>/// <param name="city">城市编码</param>/// <param name="callback">回调函数</param>publicvoidGet(stringcity, GetDataTypetype, Action<string>callback) { StartCoroutine(SendWebRequest(city, type, callback)); } privateIEnumeratorSendWebRequest(stringcity, GetDataTypetype, Action<string>callback) { //url拼接stringurl=string.Format("https://restapi.amap.com/v3/weather/weatherInfo?key={0}&city={1}&extensions={2}", key, city, type==GetDataType.Lives?"base" : "all"); //GET方式调用API服务using (UnityWebRequestrequest=UnityWebRequest.Get(url)) { DateTimebeginTime=DateTime.Now; yieldreturnrequest.SendWebRequest(); DateTimeendTime=DateTime.Now; if (request.result==UnityWebRequest.Result.Success) { Debug.Log($"{beginTime} 发起网络请求 于 {endTime} 收到响应:\r\n{request.downloadHandler.text}"); callback.Invoke(request.downloadHandler.text); } else { Debug.Log($"发起网络请求失败:{request.error}"); } } } privatevoidOnDestroy() { instance=null; } }
调用实况天气数据测试(320115代表南京市江宁区,具体城市区域编码参考城市编码表,于高德开放平台下载):
Weather.Instance.Get("320115", Weather.GetDataType.Lives, data=> { });
调用预测天气数据测试:
Weather.Instance.Get("320115", Weather.GetDataType.Forecast, data=> { });
最终运用接口响应的数据,需要定义响应数据结构,将字符串数据反序列化为我们定义的类,参数说明:
usingSystem; [Serializable] /// <summary>/// 天气API响应数据结构/// </summary>publicclassWeatherResponse{ /// <summary>/// 返回状态 1成功/0失败/// </summary>publicintstatus; /// <summary>/// 返回结果总数目/// </summary>publicintcount; /// <summary>/// 返回的状态信息/// </summary>publicstringinfo; /// <summary>/// 返回状态说明 10000代表正确/// </summary>publicintinfoCode; /// <summary>/// 实况天气数据信息/// </summary>publicWeatherLive[] lives; /// <summary>/// 预报天气信息数据/// </summary>publicWeatherForecast[] forecast; } [Serializable] /// <summary>/// 实况天气数据/// </summary>publicclassWeatherLive{ /// <summary>/// 省份名/// </summary>publicstringprovince; /// <summary>/// 城市名/// </summary>publicstringcity; /// <summary>/// 区域编码/// </summary>publicstringadcode; /// <summary>/// 天气现象(汉字描述)/// </summary>publicstringweather; /// <summary>/// 实时气温 单位:摄氏度/// </summary>publicinttemperature; /// <summary>///风向描述 /// </summary>publicstringwinddirection; /// <summary>/// 风力级别 单位:级/// </summary>publicintwindpower; /// <summary>/// 空气适度/// </summary>publicinthumidity; /// <summary>/// 数据发布时间/// </summary>publicstringreporttime; } [Serializable] /// <summary>/// 预报天气数据/// </summary>publicclassWeatherForecast{ /// <summary>/// 省份名称/// </summary>publicstringprovince; /// <summary>/// 城市名称/// </summary>publicstringcity; /// <summary>/// 城市编码/// </summary>publicintadcode; /// <summary>/// 预报发布时间/// </summary>publicstringreporttime; /// <summary>/// 预报数据列表/// </summary>publicCastInfo[] casts; } [Serializable] publicclassCastInfo{ /// <summary>/// 日期/// </summary>publicstringdate; /// <summary>/// 星期几/// </summary>publicintweek; /// <summary>/// 白天天气现象/// </summary>publicstringdayweather; /// <summary>/// 晚上天气现象/// </summary>publicstringnightweather; /// <summary>/// 白天温度/// </summary>publicintdaytemp; /// <summary>/// 晚上温度/// </summary>publicintnighttemp; /// <summary>/// 白天风向/// </summary>publicstringdaywind; /// <summary>/// 晚上风向/// </summary>publicstringnightwind; /// <summary>/// 白天风力/// </summary>publicintdaypower; /// <summary>/// 晚上风力/// </summary>publicintnightpower; }
使用Unity内置序列化/反序列化工具类JsonUtility将数据反序列化:
Weather.Instance.Get("320115", Weather.GetDataType.Forecast, data=>{ WeatherResponseresponse=JsonUtility.FromJson<WeatherResponse>(data); //TODO});