75 lines
2.3 KiB
C#
75 lines
2.3 KiB
C#
using UnityEngine;
|
|
using UnityEngine.Networking;
|
|
using Newtonsoft.Json;
|
|
using Cysharp.Threading.Tasks;
|
|
using System.Collections.Generic;
|
|
|
|
/// <summary>
|
|
/// 异步封装unityWebRequest请求
|
|
/// </summary>
|
|
public static class AsyncWebReq
|
|
{
|
|
|
|
/// <summary>
|
|
/// Get
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
/// <param name="url">地址</param>
|
|
/// <param name="_hend">头文件,登录令牌</param>
|
|
/// <param name="_token">token</param>
|
|
/// <returns></returns>
|
|
public static async UniTask<T> Get<T>(string url, string _hend = null, string _token = null)
|
|
{
|
|
UnityWebRequest getRequest = UnityWebRequest.Get(url);
|
|
if (_hend != null && _token != null)
|
|
{
|
|
getRequest.SetRequestHeader("AddHeader", _hend);
|
|
getRequest.SetRequestHeader("Hulk-Auth", _token);
|
|
await getRequest.SendWebRequest();
|
|
}
|
|
else
|
|
await getRequest.SendWebRequest();
|
|
#if UNITY_EDITOR
|
|
//Debug.Log("async req : " + getRequest.downloadHandler.text);
|
|
#endif
|
|
|
|
T result = JsonConvert.DeserializeObject<T>(getRequest.downloadHandler.text);
|
|
getRequest.Dispose();
|
|
return result;
|
|
}
|
|
/// <summary>
|
|
/// Post
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
/// <param name="url">地址</param>
|
|
/// <param name="_dic"></param>
|
|
/// <param name="_hend"></param>
|
|
/// <param name="_token"></param>
|
|
/// <returns></returns>
|
|
public static async UniTask<T> Post<T>(string url, Dictionary<string, string> _dic, string _hend = null, string _token = null)
|
|
{
|
|
|
|
WWWForm form = new WWWForm();
|
|
foreach (var item in _dic)
|
|
{
|
|
form.AddField(item.Key, item.Value);
|
|
}
|
|
var postRequest = UnityWebRequest.Post(url, form);
|
|
if (_hend != null && _token != null)
|
|
{
|
|
postRequest.SetRequestHeader("AddHeader", _hend);
|
|
postRequest.SetRequestHeader("Hulk-Auth", _token);
|
|
await postRequest.SendWebRequest();
|
|
}
|
|
else
|
|
await postRequest.SendWebRequest();
|
|
|
|
#if UNITY_EDITOR
|
|
//Debug.Log("async req : " + postRequest.downloadHandler.text);
|
|
#endif
|
|
T result = JsonConvert.DeserializeObject<T>(postRequest.downloadHandler.text);
|
|
postRequest.Dispose();
|
|
return result;
|
|
}
|
|
}
|