在这里插入代码片
```using LitJson;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.Networking;
public delegate void WeatherLivesCallBack(WeatherResponse response);
public class WeatherAutoNavi : MonoBehaviour
{
public WeatherLivesCallBack mWeatherLivesCallBack; // 获取实况天气
public WeatherLivesCallBack mWeatherForecastCallBack; // 获取预报天气
private float mDealyLivesTime = 300f; // 实时天气的刷新时间
private float mDealyForecastTime = 600.0f; //3天天气的刷新时间
private string mCityCode = "110000"; //默认北京
//密钥 于高德开发者平台创建应用申请获得
private const string key = "";
// 天气图标
public Dictionary<string, string[]> mWeatherIcon = new Dictionary<string, string[]>()
{
{ "风",new string[]{ "有风", "平静", "微风", "和风", "清风", "强风/劲风", "疾风", "大风", "烈风", "风暴", "狂爆风", "飓风", "热带风暴", "龙卷风"}},
{ "多云",new string[]{"少云", "晴间多云", "多云"} },
{ "雪",new string[]{ "雪", "阵雪", "小雪", "中雪", "大雪", "暴雪", "小雪-中雪", "中雪-大雪", "大雪-暴雪", "冷"}},
{ "雾",new string[]{ "浮尘", "扬沙", "沙尘暴", "强沙尘暴", "雾", "浓雾", "强浓雾", "轻雾", "大雾", "特强浓雾" }},
{ "晴",new string[]{ "晴", "热" }},
{ "雨夹雪",new string[]{ "雨雪天气", "雨夹雪", "阵雨夹雪"}},
{ "雨",new string[]{ "阵雨", "雷阵雨", "雷阵雨并伴有冰雹", "小雨", "中雨", "大雨", "暴雨", "大暴雨", "特大暴雨", "强阵雨", "强雷阵雨", "极端降雨", "毛毛雨/细雨", "雨", "小雨-中雨", "中雨-大雨", "大雨-暴雨", "暴雨-大暴雨", "大暴雨-特大暴雨", "冻雨"}},
{ "阴",new string[]{ "阴", "霾", "中度霾", "重度霾", "严重霾", "未知" }}
};
public Dictionary<int, string> mWeekDate = new Dictionary<int, string>(){
{1,"星期一"}, {2,"星期二"},{3,"星期三" },{4,"星期四"},{5,"星期五"},{6,"星期六"},{7,"星期日"}
};
private static WeatherAutoNavi instance;
public static WeatherAutoNavi Instance
{
get
{
if (instance == null)
{
instance = new GameObject("[Weather]").AddComponent<WeatherAutoNavi>();
DontDestroyOnLoad(instance);
}
return instance;
}
}
public void InitGame()
{
GetAddress(GetIP());
}
public void Update()
{
mDealyLivesTime -= Time.deltaTime;
mDealyForecastTime -= Time.deltaTime;
if (mDealyLivesTime <= 0.0f)
{
mDealyLivesTime = 300.0f;
Get(mCityCode, GetDataType.Lives, null);
Debug.Log("更新实时天气!!");
}
if (mDealyForecastTime <= 0.0f)
{
mDealyForecastTime = 600.0f;
Get(mCityCode, GetDataType.Forecast, null);
Debug.Log("更新预报天气!!");
}
}
public string GetIconName(string weather)
{
foreach (var weath in mWeatherIcon)
{
foreach (var item in weath.Value)
{
if (item == weather)
{
return weath.Key;
}
}
}
return string.Empty;
}
public string GetWeek(int day)
{
if (mWeekDate.ContainsKey(day))
{
return mWeekDate[day];
}
return string.Empty;
}
/// <summary>
/// 获取IP地址
/// </summary>
/// <returns></returns>
public static string GetIP()
{
try
{
string url = "http://pv.sohu.com/cityjson?ie=utf-8";
byte[] data = HttpManager.DownloadFile(url);
String ip = Encoding.UTF8.GetString(data);
Match rebool = Regex.Match(ip, @"\d{2,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}");
string outIp = rebool.Value;
return outIp;
}
catch (Exception)
{
return String.Empty;
}
}
/// <summary>
/// 获取天气数据
/// </summary>
/// <param name="city">城市编码</param>
/// <param name="callback">回调函数</param>
public void Get(string city, GetDataType type, Action<WeatherResponse> callback)
{
StartCoroutine(SendWebRequest(city, type, callback));
}
/// <summary>
/// IP 定位
/// </summary>
/// <param name="IP"></param>
public void GetAddress(string IP)
{
Dictionary<string, string> dicValue = new Dictionary<string, string>();
dicValue.Add("key", key);
dicValue.Add("ip", IP);
string urlValue = HttpManager.generateHttpGet("https://restapi.amap.com/v3/ip", dicValue);
HttpManager.HttpWebRequestGet(urlValue, OnHttpWebRequestAddressCallback);
}
/// <summary>
/// 获取cityCode
/// </summary>
/// <param name="data"></param>
/// <param name="userData"></param>
public void OnHttpWebRequestAddressCallback(JsonData data, object userData)
{
IPAddress ipAddress = JsonUtility.FromJson<IPAddress>(data.ToJson());
if (ipAddress != null)
{
mCityCode = ipAddress.adcode;
Debug.Log("mcitycode:" + mCityCode);
}
SendWeatherWebRequest();
}
public void SendWeatherWebRequest()
{
WeatherAutoNavi.Instance.Get(mCityCode, GetDataType.Forecast, null);
WeatherAutoNavi.Instance.Get(mCityCode, GetDataType.Lives, null);
}
private IEnumerator SendWebRequest(string city, GetDataType type, Action<WeatherResponse> 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}");
string data = request.downloadHandler.text;
WeatherResponse weatherResponse = JsonUtility.FromJson<WeatherResponse>(data);
if (weatherResponse != null)
{
if (weatherResponse.status == 1 && weatherResponse.infocode == 10000)
{
if (type == GetDataType.Lives)
{
if (mWeatherLivesCallBack != null)
{
mWeatherLivesCallBack(weatherResponse);
}
}
else if (type == GetDataType.Forecast)
{
if (mWeatherForecastCallBack != null)
{
mWeatherForecastCallBack(weatherResponse);
}
}
if (callback != null)
{
callback.Invoke(weatherResponse);
}
}
}
}
else
{
Debug.Log($"发起网络请求失败:{request.error}");
}
}
}
private void OnDestroy()
{
instance = null;
}
}
public enum GetDataType
{
/// <summary>
/// 获取实况天气
/// </summary>
Lives,
/// <summary>
/// 获取预报天气
/// </summary>
Forecast
}
#region 高德天气类
[Serializable]
/// <summary>
/// 天气API响应数据结构
/// </summary>
///
public class IPAddress
{
/// <summary>
/// 返回状态 1成功/0失败
/// </summary>
public int status;
/// <summary>
/// 返回的状态信息
/// </summary>
public string info;
/// <summary>
/// 返回状态说明 10000代表正确
/// </summary>
public int infocode;
/// <summary>
/// 省份名称
/// </summary>
public string province;
/// <summary>
/// 城市名称
/// </summary>
public string city;
/// <summary>
/// 城市的adcode编码
/// </summary>
public string adcode;
/// <summary>
/// 所在城市矩形区域范围
/// </summary>
public string rectangle;
}
public class WeatherResponse
{
/// <summary>
/// 返回状态 1成功/0失败
/// </summary>
public int status;
/// <summary>
/// 返回结果总数目
/// </summary>
public int count;
/// <summary>
/// 返回的状态信息
/// </summary>
public string info;
/// <summary>
/// 返回状态说明 10000代表正确
/// </summary>
public int infocode;
/// <summary>
/// 实况天气数据信息
/// </summary>
public WeatherLive[] lives;
/// <summary>
/// 预报天气信息数据
/// </summary>
public WeatherForecast[] forecasts;
}
[Serializable]
/// <summary>
/// 实况天气数据
/// </summary>
public class WeatherLive
{
/// <summary>
/// 省份名
/// </summary>
public string province;
/// <summary>
/// 城市名
/// </summary>
public string city;
/// <summary>
/// 区域编码
/// </summary>
public string adcode;
/// <summary>
/// 天气现象(汉字描述)
/// </summary>
public string weather;
/// <summary>
/// 实时气温 单位:摄氏度
/// </summary>
public int temperature;
/// <summary>
///风向描述
/// </summary>
public string winddirection;
/// <summary>
/// 风力级别 单位:级
/// </summary>
public string windpower;
/// <summary>
/// 空气适度
/// </summary>
public int humidity;
/// <summary>
/// 数据发布时间
/// </summary>
public string reporttime;
}
[Serializable]
/// <summary>
/// 预报天气数据
/// </summary>
public class WeatherForecast
{
/// <summary>
/// 省份名称
/// </summary>
public string province;
/// <summary>
/// 城市名称
/// </summary>
public string city;
/// <summary>
/// 城市编码
/// </summary>
public int adcode;
/// <summary>
/// 预报发布时间
/// </summary>
public string reporttime;
/// <summary>
/// 预报数据列表
/// </summary>
public CastInfo[] casts;
}
[Serializable]
public class CastInfo
{
/// <summary>
/// 日期
/// </summary>
public string date;
/// <summary>
/// 星期几
/// </summary>
public int week;
/// <summary>
/// 白天天气现象
/// </summary>
public string dayweather;
/// <summary>
/// 晚上天气现象
/// </summary>
public string nightweather;
/// <summary>
/// 白天温度
/// </summary>
public int daytemp;
/// <summary>
/// 晚上温度
/// </summary>
public int nighttemp;
/// <summary>
/// 白天风向
/// </summary>
public string daywind;
/// <summary>
/// 晚上风向
/// </summary>
public string nightwind;
/// <summary>
/// 白天风力
/// </summary>
public string daypower;
/// <summary>
/// 晚上风力
/// </summary>
public string nightpower;
}
#endregion
```csharp
在这里插入代using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Threading;
using LitJson;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using UnityEngine;
public delegate void OnHttpWebRequestCallback(JsonData data, object userData);
public class HttpManager :MonoBehaviour
{
//public static HttpManager mInstance;
protected static List<Thread> mHttpThreadList = new List<Thread>();
protected static ThreadLock ThreadListLock = new ThreadLock ();
private static bool NoUpdate = true;
private static List<ObjectCallBack> UpdateQueue = new List<ObjectCallBack>();
private static List<ObjectCallBack> UpdateRunQueue = new List<ObjectCallBack>();
public static void ExecuteUpdate(ObjectCallBack action)
{
lock (UpdateQueue)
{
UpdateQueue.Add(action);
NoUpdate = false;
}
}
public static void Init()
{
//mInstance = this;
GameObject gameObj = new GameObject("HttpManager");
gameObj.AddComponent<HttpManager>();
DontDestroyOnLoad(gameObj);
}
private void Update()
{
lock (UpdateQueue)
{
if (NoUpdate) return;
UpdateRunQueue.AddRange(UpdateQueue);
UpdateQueue.Clear();
NoUpdate = true;
for (var i = 0; i < UpdateRunQueue.Count; i++)
{
var action = UpdateRunQueue[i];
if (action == null) continue;
action.mCallBack(action.mJsonData,action.mUserData);
}
UpdateRunQueue.Clear();
}
}
public void Destroy()
{
ThreadListLock.waitForUnlock();
int count = mHttpThreadList.Count;
for(int i = 0; i < count; ++i)
{
mHttpThreadList[i].Abort();
mHttpThreadList[i] = null;
}
mHttpThreadList.Clear();
mHttpThreadList = null;
ThreadListLock.unlock();
}
// 同步下载文件
public static byte[] DownloadFile(string url)
{
Debug.Log("开始http下载:" + url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream inStream = response.GetResponseStream();//获取http
MemoryStream downloadStream = new MemoryStream();
byte[] tempBytes = new byte[1024];
int readCount = 0;
do
{
// 从输入流中读取数据放入内存中
readCount = inStream.Read(tempBytes, 0, tempBytes.Length);//读流
downloadStream.Write(tempBytes, 0, readCount);//写流
} while (readCount > 0);
byte[] dataBytes = downloadStream.ToArray();
downloadStream.Close();
inStream.Close();
response.Close();
Debug.Log("http下载完成:" + url);
return dataBytes;
}
public static JsonData HttpWebRequestPostFile(string url, List<FormItem> itemList, OnHttpWebRequestCallback callback, object callbakcUserData, bool logError)
{
// 以模拟表单的形式上传数据
string boundary = "----" + DateTime.Now.Ticks.ToString("x");
string fileFormdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + "\r\nContent-Type: application/octet-stream" + "\r\n\r\n";
string dataFormdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"" + "\r\n\r\n{1}";
MemoryStream postStream = new MemoryStream();
foreach (var item in itemList)
{
string formdata = null;
if (item.mFileContent != null)
{
formdata = string.Format(fileFormdataTemplate, "fileContent", item.mFileName);
}
else
{
formdata = string.Format(dataFormdataTemplate, item.mKey, item.mValue);
}
// 统一处理
byte[] formdataBytes = null;
// 第一行不需要换行
if (postStream.Length == 0)
{
formdataBytes = StringToBytes(formdata.Substring(2, formdata.Length - 2), Encoding.UTF8);
}
else
{
formdataBytes = StringToBytes(formdata, Encoding.UTF8);
}
postStream.Write(formdataBytes, 0, formdataBytes.Length);
// 写入文件内容
if (item.mFileContent != null && item.mFileContent.Length > 0)
{
postStream.Write(item.mFileContent, 0, item.mFileContent.Length);
}
}
// 结尾
var footer = StringToBytes("\r\n--" + boundary + "--\r\n", Encoding.UTF8);
postStream.Write(footer, 0, footer.Length);
byte[] postBytes = postStream.ToArray();
ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
webRequest.Method = "POST";
webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
webRequest.Timeout = 10000;
webRequest.Credentials = CredentialCache.DefaultCredentials;
webRequest.ContentLength = postBytes.Length;
// 异步
if (callback != null)
{
RequestThreadParam threadParam = new RequestThreadParam();
threadParam.mRequest = webRequest;
threadParam.mByteArray = postBytes;
threadParam.mCallback = callback;
threadParam.mUserData = callbakcUserData;
threadParam.mFullURL = url;
threadParam.mLogError = logError;
Thread httpThread = new Thread(WaitPostHttpWebRequest);
threadParam.mThread = httpThread;
httpThread.Start(threadParam);
httpThread.IsBackground = true;
ThreadListLock.waitForUnlock();
mHttpThreadList.Add(httpThread);
ThreadListLock.unlock();
return null;
}
// 同步
else
{
try
{
// 3. 附加要POST给服务器的数据到HttpWebRequest对象(附加POST数据的过程比较特殊,它并没有提供一个属性给用户存取,需要写入HttpWebRequest对象提供的一个stream里面。)
Stream newStream = webRequest.GetRequestStream();//创建一个Stream,赋值是写入HttpWebRequest对象提供的一个stream里面
newStream.Write(postBytes, 0, postBytes.Length);
newStream.Close();
// 4. 读取服务器的返回信息
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string phpend = php.ReadToEnd();
php.Close();
response.Close();
return JsonMapper.ToObject(phpend);
}
catch (Exception)
{
return null;
}
}
}
public static JsonData HttpWebRequestPost(string url, byte[] data, string contentType, OnHttpWebRequestCallback callback, object callbakcUserData, bool logError)
{
// 初始化新的webRequst
// 1. 创建httpWebRequest对象
ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
// 2. 初始化HttpWebRequest对象
webRequest.Method = "POST";
webRequest.ContentType = contentType;
webRequest.ContentLength = data.Length;
webRequest.Credentials = CredentialCache.DefaultCredentials;
webRequest.Timeout = 10000;
// 异步
if (callback != null)
{
RequestThreadParam threadParam = new RequestThreadParam();
threadParam.mRequest = webRequest;
threadParam.mByteArray = data;
threadParam.mCallback = callback;
threadParam.mUserData = callbakcUserData;
threadParam.mFullURL = url;
threadParam.mLogError = logError;
Thread httpThread = new Thread(WaitPostHttpWebRequest);
threadParam.mThread = httpThread;
httpThread.Start(threadParam);
httpThread.IsBackground = true;
ThreadListLock.waitForUnlock();
mHttpThreadList.Add(httpThread);
ThreadListLock.unlock();
return null;
}
// 同步
else
{
try
{
// 3. 附加要POST给服务器的数据到HttpWebRequest对象(附加POST数据的过程比较特殊,它并没有提供一个属性给用户存取,需要写入HttpWebRequest对象提供的一个stream里面。)
Stream newStream = webRequest.GetRequestStream();//创建一个Stream,赋值是写入HttpWebRequest对象提供的一个stream里面
newStream.Write(data, 0, data.Length);
newStream.Close();
// 4. 读取服务器的返回信息
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string phpend = php.ReadToEnd();
php.Close();
response.Close();
return JsonMapper.ToObject(phpend);
}
catch (Exception)
{
return null;
}
}
}
public static JsonData httpWebRequestPost(string url, byte[] data, OnHttpWebRequestCallback callback = null, object callbakcUserData = null, bool logError = true)
{
return HttpWebRequestPost(url, data, "application/x-www-form-urlencoded", callback, callbakcUserData, logError);
}
public static JsonData httpWebRequestPost(string url, string param, OnHttpWebRequestCallback callback = null, object callbakcUserData = null, bool logError = true)
{
return HttpWebRequestPost(url, StringToBytes(param, Encoding.UTF8), "application/x-www-form-urlencoded", callback, callbakcUserData, logError);
}
public static JsonData httpWebRequestPost(string url, string param, string contentType, OnHttpWebRequestCallback callback = null, object callbakcUserData = null, bool logError = true)
{
return HttpWebRequestPost(url, StringToBytes(param, Encoding.UTF8), contentType, callback, callbakcUserData, logError);
}
static public string generateHttpGet(string url, Dictionary<string, string> get)
{
string Parameters = "";
if (get.Count > 0)
{
Parameters = "?";
//从集合中取出所有参数,设置表单参数(AddField()).
foreach (KeyValuePair<string, string> post_arg in get)
{
Parameters += post_arg.Key + "=" + post_arg.Value + "&";
}
removeLast(ref Parameters, '&');
}
return url + Parameters;
}
public static void removeLast(ref string stream, char key)
{
int lastCommaPos = stream.LastIndexOf(key);
if (lastCommaPos != -1)
{
stream = stream.Remove(lastCommaPos, 1);
}
}
public static JsonData HttpWebRequestGet(string urlString, OnHttpWebRequestCallback callback = null, bool logError = true)
{
HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(new Uri(urlString));//根据url地址创建HTTpWebRequest对象
httprequest.Method = "GET";
httprequest.KeepAlive = false;//持久连接设置为false
httprequest.ProtocolVersion = HttpVersion.Version11;// 网络协议的版本
httprequest.ContentType = "application/x-www-form-urlencoded";//http 头
httprequest.AllowAutoRedirect = true;
httprequest.MaximumAutomaticRedirections = 2;
httprequest.Timeout = 10000;//设定超时10秒(毫秒)
// 异步
if (callback != null)
{
RequestThreadParam threadParam = new RequestThreadParam();
threadParam.mRequest = httprequest;
threadParam.mByteArray = null;
threadParam.mCallback = callback;
threadParam.mFullURL = urlString;
threadParam.mLogError = logError;
Thread httpThread = new Thread(waitGetHttpWebRequest);
threadParam.mThread = httpThread;
httpThread.Start(threadParam);
httpThread.IsBackground = true;
ThreadListLock.waitForUnlock();
mHttpThreadList.Add(httpThread);
ThreadListLock.unlock();
return null;
}
// 同步
else
{
try
{
HttpWebResponse response = (HttpWebResponse)httprequest.GetResponse();
Stream steam = response.GetResponseStream();
StreamReader reader = new StreamReader(steam, Encoding.UTF8);
string pageStr = reader.ReadToEnd();
reader.Close();
response.Close();
httprequest.Abort();
reader = null;
response = null;
httprequest = null;
return JsonMapper.ToObject(pageStr);
}
catch (Exception)
{
return null;
}
}
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
static protected void WaitPostHttpWebRequest(object param)
{
RequestThreadParam threadParam = param as RequestThreadParam;
try
{
//3. 附加要POST给服务器的数据到HttpWebRequest对象(附加POST数据的过程比较特殊,它并没有提供一个属性给用户存取,需要写入HttpWebRequest对象提供的一个stream里面。)
Stream newStream = threadParam.mRequest.GetRequestStream();//创建一个Stream,赋值是写入HttpWebRequest对象提供的一个stream里面
newStream.Write(threadParam.mByteArray, 0, threadParam.mByteArray.Length);
newStream.Close();
//4. 读取服务器的返回信息
HttpWebResponse response = (HttpWebResponse)threadParam.mRequest.GetResponse();
StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string phpend = php.ReadToEnd();
php.Close();
response.Close();
php = null;
response = null;
threadParam.mRequest.Abort();
threadParam.mRequest = null;
//threadParam.mCallback(JsonMapper.ToObject(phpend), threadParam.mUserData);
ObjectCallBack callback = new ObjectCallBack();
callback.mCallBack = threadParam.mCallback;
callback.mJsonData = JsonMapper.ToObject(phpend);
callback.mUserData = threadParam.mUserData;
ExecuteUpdate(callback);
}
catch (Exception e)
{
//threadParam.mCallback(null, threadParam.mUserData);
string info = "http post result exception:" + e.Message + ", url:" + threadParam.mFullURL;
Debug.Log(info);
}
finally
{
ThreadListLock.waitForUnlock();
if(mHttpThreadList != null)
{
mHttpThreadList.Remove(threadParam.mThread);
}
ThreadListLock.unlock();
}
}
static protected void waitGetHttpWebRequest(object param)
{
RequestThreadParam threadParam = param as RequestThreadParam;
try
{
HttpWebResponse response = (HttpWebResponse)threadParam.mRequest.GetResponse();
Stream steam = response.GetResponseStream();
StreamReader reader = new StreamReader(steam, Encoding.UTF8);
string pageStr = reader.ReadToEnd();
reader.Close();
response.Close();
reader = null;
response = null;
threadParam.mRequest.Abort();
threadParam.mRequest = null;
//threadParam.mCallback(JsonMapper.ToObject(pageStr), threadParam.mUserData);
ObjectCallBack callback = new ObjectCallBack();
callback.mCallBack = threadParam.mCallback;
callback.mJsonData = JsonMapper.ToObject(pageStr);
callback.mUserData = threadParam.mUserData;
ExecuteUpdate(callback);
}
catch (Exception e)
{
ObjectCallBack callback = new ObjectCallBack();
callback.mCallBack = threadParam.mCallback;
callback.mJsonData = "";
callback.mUserData = null;
ExecuteUpdate(callback);
//threadParam.mCallback(null, threadParam.mUserData);
string info = "http get result exception : " + e.Message + ", url : " + threadParam.mFullURL;
Debug.Log(info);
}
finally
{
ThreadListLock.waitForUnlock();
if(mHttpThreadList != null)
{
mHttpThreadList.Remove(threadParam.mThread);
}
ThreadListLock.unlock();
}
}
protected static bool MyRemoteCertificateValidationCallback(System.Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
bool isOk = true;
// If there are errors in the certificate chain,
// look at each error to determine the cause.
if (sslPolicyErrors != SslPolicyErrors.None)
{
for (int i = 0; i < chain.ChainStatus.Length; i++)
{
if (chain.ChainStatus[i].Status == X509ChainStatusFlags.RevocationStatusUnknown)
{
continue;
}
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
bool chainIsValid = chain.Build((X509Certificate2)certificate);
if (!chainIsValid)
{
isOk = false;
break;
}
}
}
return isOk;
}
public static byte[] StringToBytes(string str, Encoding encoding)
{
return encoding.GetBytes(str);
}
}
public class RequestThreadParam
{
public HttpWebRequest mRequest;
public byte[] mByteArray;
public OnHttpWebRequestCallback mCallback;
public object mUserData;
public Thread mThread;
public string mFullURL;
public bool mLogError;
}
// 作为字段参数时,只填写mKey和mValue
// 作为文件内容时,只填写mFileContont和mFileName
public class FormItem
{
public byte[] mFileContent;
public string mFileName;
public string mKey;
public string mValue;
public FormItem(byte[] file, string fileName)
{
mFileContent = file;
mFileName = fileName;
}
public FormItem(string key, string value)
{
mKey = key;
mValue = value;
}
}
public class ObjectCallBack
{
public OnHttpWebRequestCallback mCallBack;
public JsonData mJsonData;
public object mUserData;
}码片
Unity高德定位获取天气预报
于 2022-08-13 16:53:12 首次发布