2025-04-23 13:36:40 +08:00

73 lines
2.4 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using ZXKFramework;
public class HttpRestful : SingletonDdol<HttpRestful>
{
public void Get(string url, Action<bool, string> actionResult = null)
{
StartCoroutine(_Get(url, actionResult));
}
private IEnumerator _Get(string url, Action<bool, string> action)
{
using (UnityWebRequest request = UnityWebRequest.Get(url))
{
yield return request.SendWebRequest();
string resstr = "";
if (request.isNetworkError || request.isHttpError)
{
resstr = request.error;
}
else
{
resstr = request.downloadHandler.text;
}
if (action != null)
{
action(request.isHttpError, resstr);
}
}
}
public void Post(string url, string form, Action<bool, DownloadHandler> callBack, string Header = null, string HeaderValue = null, int timeOut = 3)
{
StartCoroutine(_Post(url, form, callBack, Header, HeaderValue, timeOut));
}
public IEnumerator _Post(string url, string form, Action<bool, DownloadHandler> callBack, string Header = null, string HeaderValue = null, int timeOut = 3)
{
//请求链接并将form对象发送到远程服务器
using (UnityWebRequest webRequest = UnityWebRequest.Post(url, form, "application/json"))//;charset=utf-8
{
if (!string.IsNullOrEmpty(Header) && !string.IsNullOrEmpty(HeaderValue))
{
webRequest.SetRequestHeader(Header, HeaderValue);
}
webRequest.timeout = timeOut * 1000;
yield return webRequest.SendWebRequest();
if (webRequest.result!= UnityWebRequest.Result.Success)
{
Debug.Log(webRequest.error);
callBack?.Invoke(false, webRequest.downloadHandler);
}
else
{
callBack?.Invoke(true, webRequest.downloadHandler);
}
//if (webRequest.isHttpError || webRequest.isNetworkError)
//{
// //Debug.LogError("===========");
// callBack?.Invoke(false, null);
//}
//else
//{
// callBack?.Invoke(true, webRequest.downloadHandler);
//}
};
}
}