接入接口前首先申请应用密钥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<Weather>();
DontDestroyOnLoad(instance);
}
return instance;
}
}
private const string key = "";
public enum GetDataType
{
Lives,
Forecast
}
public void Get(string city, GetDataType type, Action<string> callback)
{
StartCoroutine(SendWebRequest(city, type, callback));
}
private IEnumerator SendWebRequest(string city, GetDataType type, Action<string> callback)
{
string url = string.Format("https://restapi.amap.com/v3/weather/weatherInfo?key={0}&city={1}&extensions={2}", key, city, type == GetDataType.Lives ? "base" : "all");
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]
public class WeatherResponse
{
public int status;
public int count;
public string info;
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<WeatherResponse>(data);
});
