接入接口前首先申请应用密钥Key,登录高德开发者开放平台,创建应用,获取密钥。
天气查询API服务地址:https://restapi.amap.com/v3/weather/weatherInfo?parameters,需以Get请求方式调用,parameters代表所有参数,参数以&进行分隔。
前两个参数为必填参数,extensions传入base代表实况天气,all代表预报天气,定义枚举用以区分:
public enum GetDataType
{
///
/// 获取实况天气
///
Lives,
///
/// 获取预报天气
///
Forecast
}
这里我们以JSON格式解析接口响应数据,所以output传入JSON。最终封装Weather天气类:
using System;
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
[AddComponentMenu("")]
public class Weather : MonoBehaviour
{
private static Weather instance;
public static Weather Instance
{
get
{
if (instance == null)
{
instance = new GameObject("[Weather]").AddComponent();
DontDestroyOnLoad(instance);
}
return instance;
}
}
//密钥 于高德开发者平台创建应用申请获得
private const string key = "";
public enum GetDataType
{
///
/// 获取实况天气
///
Lives,
///
/// 获取预报天气
///
Forecast
}
///
/// 获取天气数据
///
/// 城市编码
/// 回调函数
public void Get(string city, GetDataType type, Action callback)
{
StartCoroutine(SendWebRequest(city, type, callback));
}
private IEnumerator SendWebRequest(string city, GetDataType type, Action callback)
{
//url拼接
string url = 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 (UnityWebRequest request = UnityWebRequest.Get(url))
{
DateTime beginTime = DateTime.Now;
yield return request.SendWebRequest();
DateTime endTime = 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}");
}
}
}
private void OnDestroy()
{
instance = null;
}
}
调用实况天气数据测试(320115代表南京市江宁区,具体城市区域编码参考城市编码表,于高德开放平台下载):
Weather.Instance.Get("320115", Weather.GetDataType.Lives, data => { });
调用预测天气数据测试:
Weather.Instance.Get("320115", Weather.GetDataType.Forecast, data => { });
最终运用接口响应的数据,需要定义响应数据结构,将字符串数据反序列化为我们定义的类,参数说明:
using System;
[Serializable]
///
/// 天气API响应数据结构
///
public class WeatherResponse
{
///
/// 返回状态 1成功/0失败
///
public int status;
///
/// 返回结果总数目
///
public int count;
///
/// 返回的状态信息
///
public string info;
///
/// 返回状态说明 10000代表正确
///
public int infoCode;
///
/// 实况天气数据信息
///
public WeatherLive[] lives;
///
/// 预报天气信息数据
///
public WeatherForecast[] forecast;
}
[Serializable]
///
/// 实况天气数据
///
public class WeatherLive
{
///
/// 省份名
///
public string province;
///
/// 城市名
///
public string city;
///
/// 区域编码
///
public string adcode;
///
/// 天气现象(汉字描述)
///
public string weather;
///
/// 实时气温 单位:摄氏度
///
public int temperature;
///
///风向描述
///
public string winddirection;
///
/// 风力级别 单位:级
///
public int windpower;
///
/// 空气适度
///
public int humidity;
///
/// 数据发布时间
///
public string reporttime;
}
[Serializable]
///
/// 预报天气数据
///
public class WeatherForecast
{
///
/// 省份名称
///
public string province;
///
/// 城市名称
///
public string city;
///
/// 城市编码
///
public int adcode;
///
/// 预报发布时间
///
public string reporttime;
///
/// 预报数据列表
///
public CastInfo[] casts;
}
[Serializable]
public class CastInfo
{
///
/// 日期
///
public string date;
///
/// 星期几
///
public int week;
///
/// 白天天气现象
///
public string dayweather;
///
/// 晚上天气现象
///
public string nightweather;
///
/// 白天温度
///
public int daytemp;
///
/// 晚上温度
///
public int nighttemp;
///
/// 白天风向
///
public string daywind;
///
/// 晚上风向
///
public string nightwind;
///
/// 白天风力
///
public int daypower;
///
/// 晚上风力
///
public int nightpower;
}
使用Unity内置序列化/反序列化工具类JsonUtility将数据反序列化:
Weather.Instance.Get("320115", Weather.GetDataType.Forecast, data =>
{
WeatherResponse response = JsonUtility.FromJson(data);
//TODO
});