NewN_UAVPlane/Assets/Zion/Scripts/Adam/Utility/Net/AsyncWebReq.cs

102 lines
3.1 KiB
C#

using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Collections;
using System.Threading.Tasks;
/// <summary>
/// 异步封装unityWebRequest请求
/// </summary>
public static class AsyncWebReq
{
public static async UniTask<T> Get<T>(string endpoint)
{
//Task.Delay(10000).Wait();
var getRequest = CreateRequest(endpoint);
await getRequest.SendWebRequest();
#if UNITY_EDITOR
//Debug.Log("async Get req : " + getRequest.downloadHandler.text);
#endif
T result = JsonUtility.FromJson<T>(getRequest.downloadHandler.text);
getRequest.Dispose();
return result;
}
public static async UniTask<T> Post<T>(string endpoint, object payload)
{
//Task.Delay(10000).Wait();
var postRequest = CreateRequest(endpoint, RequestType.POST, payload);
await postRequest.SendWebRequest();
#if UNITY_EDITOR
//Debug.Log("async Post req : " + postRequest.downloadHandler.text);
//Debug.Log("endpoint : " + endpoint);
#endif
T result = JsonUtility.FromJson<T>(postRequest.downloadHandler.text);
postRequest.Dispose();
return result;
}
public static UnityWebRequest CreateRequest(string path, RequestType type = RequestType.GET, object data = null)
{
var request = new UnityWebRequest(path, type.ToString());
if (data != null)
{
string reqJson = JsonConvert.SerializeObject(data);
#if UNITY_EDITOR
Debug.Log($"async req json : {reqJson}");
#endif
var bodyRaw = Encoding.UTF8.GetBytes(reqJson);
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
}
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
return request;
}
public static IEnumerator PostData2(string url, Dictionary<string, string> keyValuePairs, System.Action<string> action = null)
{
WWWForm form = new WWWForm();
foreach (var item in keyValuePairs)
{
form.AddField(item.Key, item.Value);//把字典的键值对存到from
//Debug.LogError(item.Key + " " + item.Value);
}
UnityWebRequest request = UnityWebRequest.Post(url, form);
yield return request.SendWebRequest();//发送请求
if (request.isNetworkError || request.isHttpError)
{
Debug.Log("cannot get data:" + request.responseCode);
action(null);
}
else
{
if (!string.IsNullOrEmpty(request.downloadHandler.text))
action?.Invoke(request.downloadHandler.text);
else
action?.Invoke(null);
}
}
private static void AttachHeader(UnityWebRequest request, string key, string value)
{
request.SetRequestHeader(key, value);
}
/// <summary>
/// 请求类型
/// </summary>
public enum RequestType
{
GET = 0,
POST = 1
}
}