Cute_demon_attacks/meng_yao/Assets/communal/web/web.cs

77 lines
2.6 KiB
C#
Raw Normal View History

2024-10-29 20:47:58 +08:00
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
public class web : MonoBehaviour
{
// <20><EFBFBD><E6B4A2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ص<EFBFBD>Cookie
private static Dictionary<string, string> cookieJar = new Dictionary<string, string>();
public static async Task<string> SendRequest(string url, string method = "GET", string jsonData = "{}")
2024-10-29 20:47:58 +08:00
{
2024-10-29 20:47:58 +08:00
using (UnityWebRequest request = new UnityWebRequest(url, method))
{
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ش<EFBFBD><D8B4><EFBFBD><EFBFBD><EFBFBD>
request.downloadHandler = new DownloadHandlerBuffer();
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>POST<53><54><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
2024-10-29 20:47:58 +08:00
if (method == "POST" && jsonData != null)
{
byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonData);
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
request.SetRequestHeader("Content-Type", "application/json");
}
// <20><><EFBFBD><EFBFBD><EFBFBD>Ѵ<D1B4><E6B4A2> Cookie
if (cookieJar.Count > 0)
2024-10-29 20:47:58 +08:00
{
string cookieHeader = "";
foreach (var cookie in cookieJar)
{
cookieHeader += $"{cookie.Key}={cookie.Value}; ";
}
request.SetRequestHeader("Cookie", cookieHeader);
2024-10-29 20:47:58 +08:00
}
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>󲢵ȴ<F3B2A2B5><C8B4><EFBFBD>Ӧ
2024-10-29 20:47:58 +08:00
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
{
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ص<EFBFBD>Cookie
string setCookieHeader;
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;
Debug.Log(value);
}
}
}
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ӧ<EFBFBD><D3A6><EFBFBD><EFBFBD>
2024-10-29 20:47:58 +08:00
return request.downloadHandler.text;
}
}
}
}