79 lines
2.7 KiB
C#
79 lines
2.7 KiB
C#
using System.Collections;
|
||
using System.Collections.Generic;
|
||
using System.Text;
|
||
using System.Threading.Tasks;
|
||
using UnityEngine;
|
||
using UnityEngine.Networking;
|
||
|
||
public class web : MonoBehaviour
|
||
{
|
||
public const string URL = "http://47.109.133.52";
|
||
// 存储服务器返回的Cookie
|
||
private static Dictionary<string, string> cookieJar = new Dictionary<string, string>();
|
||
|
||
public static async Task<string> SendRequest(string url, string method = "GET", string jsonData = "{}")
|
||
{
|
||
|
||
using (UnityWebRequest request = new UnityWebRequest(url, method))
|
||
{
|
||
// 设置下载处理器
|
||
request.downloadHandler = new DownloadHandlerBuffer();
|
||
|
||
// 如果是POST请求,设置请求体
|
||
if (method == "POST" && jsonData != null)
|
||
{
|
||
byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonData);
|
||
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
|
||
request.SetRequestHeader("Content-Type", "application/json");
|
||
}
|
||
|
||
// 设置已存储的 Cookie
|
||
if (cookieJar.Count > 0)
|
||
{
|
||
string cookieHeader = "";
|
||
foreach (var cookie in cookieJar)
|
||
{
|
||
cookieHeader += $"{cookie.Key}={cookie.Value}; ";
|
||
|
||
}
|
||
request.SetRequestHeader("Cookie", cookieHeader);
|
||
}
|
||
|
||
// 发送请求并等待响应
|
||
var operation = request.SendWebRequest();
|
||
while (!operation.isDone)
|
||
await Task.Yield();
|
||
|
||
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
|
||
{
|
||
Debug.LogError($"Error: {request.error}");
|
||
return null;
|
||
}
|
||
else
|
||
{
|
||
|
||
// 处理返回的Cookie
|
||
string setCookieHeader;
|
||
string str = request.downloadHandler.text;
|
||
if (request.GetResponseHeaders().TryGetValue("Set-Cookie", out setCookieHeader))
|
||
{
|
||
string[] cookies = setCookieHeader.Split(';');
|
||
foreach (var cookie in cookies)
|
||
{
|
||
var cookieParts = cookie.Split('=');
|
||
if (cookieParts.Length == 2)
|
||
{
|
||
string key = cookieParts[0].Trim();
|
||
string value = cookieParts[1].Trim();
|
||
cookieJar[key] = value;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 返回响应内容
|
||
return request.downloadHandler.text;
|
||
}
|
||
}
|
||
}
|
||
}
|