105 lines
3.9 KiB
C#
Raw Normal View History

2025-09-08 14:51:28 +08:00
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public class HttpRestful : MonoBehaviour
{
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 result = "";
bool isSuccess = false;
// 检查请求结果包含Aborted状态的单独处理
switch (request.result)
{
case UnityWebRequest.Result.Success:
result = request.downloadHandler.text;
isSuccess = true;
break;
case UnityWebRequest.Result.ConnectionError:
result = $"连接错误: {request.error}";
isSuccess = false;
break;
case UnityWebRequest.Result.ProtocolError:
result = $"协议错误: {request.error} (状态码: {(int)request.responseCode})";
isSuccess = false;
break;
case UnityWebRequest.Result.DataProcessingError:
result = $"数据处理错误: {request.error}";
isSuccess = false;
break;
case UnityWebRequest.Result.InProgress:
result = "请求仍在进行中(未完成)";
isSuccess = false;
break;
}
// 调用回调
action?.Invoke(isSuccess, result);
}
}
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));
}
private IEnumerator _Post(string url, string jsonForm, Action<bool, DownloadHandler> callBack,
string Header = null, string HeaderValue = null, int timeOut = 3)
{
Debug.Log(jsonForm);
// 创建POST请求
using UnityWebRequest webRequest = new UnityWebRequest(url, "POST");
//// 将JSON字符串转换为字节数组
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonForm);
//// 设置上传处理器
webRequest.uploadHandler = new UploadHandlerRaw(bodyRaw);
// 设置下载处理器
webRequest.downloadHandler = new DownloadHandlerBuffer();
// 设置JSON内容类型
webRequest.SetRequestHeader("Content-Type", "application/json;charset=utf-8"); // 关键:指定字符集
webRequest.SetRequestHeader("accept", "application/json");
// 设置超时时间(毫秒)
webRequest.timeout = timeOut * 1000;
// 添加自定义头信息
if (!string.IsNullOrEmpty(Header) && !string.IsNullOrEmpty(HeaderValue))
{
webRequest.SetRequestHeader(Header, HeaderValue);
}
// 发送请求并等待响应
yield return webRequest.SendWebRequest();
// 处理响应结果
if (webRequest.result != UnityWebRequest.Result.Success)
{
string errorDetails = $"请求错误: {webRequest.error}\n" +
$"状态码: {(int)webRequest.responseCode}\n" +
$"服务器返回内容: {webRequest.downloadHandler?.text}"; // 服务器可能返回具体错误原因
Debug.LogError(errorDetails);
callBack?.Invoke(false, webRequest.downloadHandler);
}
else
{
callBack?.Invoke(true, webRequest.downloadHandler);
}
//// 释放资源
webRequest.uploadHandler.Dispose();
}
}