75 lines
2.6 KiB
C#
75 lines
2.6 KiB
C#
using System;
|
||
using System.Collections;
|
||
using System.Net;
|
||
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.result != UnityWebRequest.Result.Success)
|
||
{
|
||
resstr = request.error;
|
||
}
|
||
else
|
||
{
|
||
resstr = request.downloadHandler.text;
|
||
}
|
||
|
||
if (action != null)
|
||
{
|
||
action(request.result == UnityWebRequest.Result.ProtocolError, 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对象(JSON字符串)发送到远程服务器
|
||
using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
|
||
{
|
||
// 将form字符串转为字节数组(JSON格式)
|
||
byte[] jsonBytes = System.Text.Encoding.UTF8.GetBytes(form);
|
||
// 设置上传数据
|
||
webRequest.uploadHandler = new UploadHandlerRaw(jsonBytes);
|
||
// 设置下载处理器
|
||
webRequest.downloadHandler = new DownloadHandlerBuffer();
|
||
// 设置Content-Type为JSON
|
||
webRequest.SetRequestHeader("Content-Type", "application/json");
|
||
|
||
// 原代码的Header、timeout等逻辑保持不变
|
||
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, null);
|
||
}
|
||
else
|
||
{
|
||
callBack?.Invoke(true, webRequest.downloadHandler);
|
||
}
|
||
}
|
||
}
|
||
} |