Files
BabyVideo/Assets/Scripts/Net.cs
2026-02-09 20:10:14 +08:00

97 lines
2.6 KiB
C#
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. 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 System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;
using UnityEngine.Networking;
namespace NBF
{
[Serializable]
public class HttpResult
{
public int Code { get; set; }
public JToken Data { get; set; }
}
public class Net : MonoBehaviour
{
private string serverUrl = "http://localhost:8080";
private string serverPassword = "";
public static Net Instance { get; private set; }
private void Awake()
{
Instance = this;
}
public void SetServer(string server, string password)
{
if (!(server.StartsWith("http://") || server.StartsWith("https://")))
{
server = "http://" + server;
}
if (server.EndsWith("/"))
{
server = server.Substring(0, server.Length - 1);
}
else if (server.EndsWith("\\"))
{
server = server.Substring(0, server.Length - 1);
}
serverUrl = server;
serverPassword = password;
}
#region Post
public void Send(string action, Dictionary<string, string> form, Action<HttpResult> callback = null)
{
StartCoroutine(SendYield(action, form, callback));
}
private IEnumerator SendYield(string action, Dictionary<string, string> form,
Action<HttpResult> callback = null)
{
if (form == null)
{
form = new Dictionary<string, string>();
}
var url = serverUrl + action;
form["sign"] = serverPassword;
UnityWebRequest request = UnityWebRequest.Post(url, form);
request.downloadHandler = new DownloadHandlerBuffer();
// 4⃣ 发送
yield return request.SendWebRequest();
// 5⃣ 处理结果
if (request.result != UnityWebRequest.Result.Success)
{
Debug.LogError(request.error);
callback?.Invoke(new HttpResult()
{
Code = -1,
Data = request.error
});
}
else
{
Debug.Log("Response: " + request.downloadHandler.text);
var result = JsonConvert.DeserializeObject<HttpResult>(request.downloadHandler.text);
callback?.Invoke(result);
}
}
#endregion
}
}