Unity IP定位
CoderZ1010 人气:1一、接口介绍
Http接口,根据输入的IP地址,快速定位IP所在位置,仅支持IPV4,不支持国外IP解析。
二、申请密钥Key
1.登录高德开放平台,进入控制台
2.在应用管理中创建新的应用
3.为应用添加Key
三、在Unity中应用
1.定位数据结构
根据官方文档中给出的返回结果参数说明定义相应的数据结构
/// <summary> /// IP定位响应数据结构 /// </summary> [Serializable] public class IPLocationResponse { /// <summary> /// 返回结果状态值 /// 0表示失败 1表示成功 /// </summary> public string status; /// <summary> /// 返回状态说明 /// status为0时,info返回错误原因 否则返回OK /// </summary> public string info; /// <summary> /// 状态码 10000表示正确,详情参阅官方文档info状态表 /// </summary> public string infocode; /// <summary> /// 省份名称 /// </summary> public string province; /// <summary> /// 城市名称 /// </summary> public string city; /// <summary> /// 城市的adcode编码 /// </summary> public string adcode; /// <summary> /// 所在城市矩形区域范围 /// </summary> public string rectangle; }
2.函数封装
using System; using UnityEngine; using System.Collections; using UnityEngine.Networking; /// <summary> /// IP定位 /// </summary> public class IPLocation { //在高德开放平台创建应用获取密钥 private static readonly string key = ""; /// <summary> /// 发起网络请求 /// </summary> /// <param name="ip">要定位的IP地址</param> /// <param name="callback">回调函数</param> /// <returns></returns> public static IEnumerator SendWebRequest(string ip, Action<IPLocationResponse> callback) { string url = string.Format("https://restapi.amap.com/v3/ip?key={0}&ip={1}", key, ip); using(UnityWebRequest request = UnityWebRequest.Get(url)) { yield return request.SendWebRequest(); if (!request.isHttpError && !request.isNetworkError) { Debug.Log(request.downloadHandler.text); IPLocationResponse response = JsonUtility.FromJson<IPLocationResponse>(request.downloadHandler.text); callback?.Invoke(response); } else { Debug.Log("调用IP定位接口失败:" + request.error.ToString()); } } } }
3.测试
using UnityEngine; public class IPLocationExample : MonoBehaviour { private void Start() { StartCoroutine(IPLocation.SendWebRequest("114.222.121.24", s => { })); } }
加载全部内容