简化api调用流程,非常奈斯。
2024.9.17 调整脚本,RestWebClient新增基础url,请求、响应增加json解析,成功与失败分开处理。
RestWebClient.cs
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
namespace MYTOOL.RestClient
{
/// <summary>
/// UnityWebRequest封装类
/// </summary>
public class RestWebClient
{
private readonly MonoBehaviour executer;
private readonly string baseUrl;
public RestWebClient(MonoBehaviour executer, string baseUrl = "")
{
if (executer == null) throw new ArgumentNullException(nameof(executer));
this.executer = executer;
this.baseUrl = baseUrl;
}
#region >> GET
public void Get(string url, Request req)
{
if (req == null) throw new ArgumentNullException(nameof(req));
executer.StartCoroutine(InnerGet(baseUrl + url, req));
}
#endregion
#region >> PUT
public void Put(string url, Request req)
{
if (req == null) throw new ArgumentNullException(nameof(req));
executer.StartCoroutine(InnerPut(baseUrl + url, req));
}
#endregion
#region >> POST
public void Post(string url, Request req)
{
if (req == null) throw new ArgumentNullException(nameof(req));
executer.StartCoroutine(InnerPost(baseUrl + url, req));
}
#endregion
#region >> DELETE
public void Delete(string url, Request req)
{
if (req == null) throw new ArgumentNullException(nameof(req));
executer.StartCoroutine(InnerDelete(baseUrl + url, req));
}
#endregion
private IEnumerator InnerGet(string url, Request req)
{
req.InvokeOnBegin();
byte retryCount = req.RetryCount;
do
{
using UnityWebRequest webRequest = UnityWebRequest.Get(url);
InitUnityWebRequest(webRequest, req);
webRequest.SendWebRequest();
while (!webRequest.isDone)
{
if (req.IsAbort)
{
webRequest.Abort();
req.InvokeOnAbort();
yield break;
}
yield return null;
}
bool isSuccess = webRequest.result == UnityWebRequest.Result.Success;
if (isSuccess || retryCount == 0)
{
LogInfo($"[{
webRequest.method} {
webRequest.responseCode}] Url: {
webRequest.url}", webRequest.error);
req.InvokeOnComplete(isSuccess, webRequest.responseCode, webRequest.downloadHandler.data, webRequest.error);
yield break;
}
if (req.RetryInterval > 0.001)
{
yield return new WaitForSeconds(req.RetryInterval);
}
} while (retryCount-- > 0);
}
private IEnumerator InnerPut(string url, Request req)
{
req.InvokeOnBegin();
byte[] bodyData = req.FormData != null ? req.FormData.data : req.BodyData;
byte retryCount = req.RetryCount;
do
{
using UnityWebRequest webRequest = UnityWebRequest.Put(url, bodyData);
InitUnityWebRequest(webRequest, req);
webRequest.SendWebRequest();
while (!webRequest.isDone)
{
if (req.IsAbort)
{
webRequest.Abort();
req.InvokeOnAbort();
yield break;
}
yield return null;
}
bool isSuccess = webRequest.result == UnityWebRequest.Result.Success;
if (isSuccess || retryCount == 0)
{
LogInfo($"[{
webRequest.method}