55 lines
1.7 KiB
C#
55 lines
1.7 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.Text;
|
|
using UnityEngine;
|
|
using UnityEngine.Networking;
|
|
|
|
// http请求处理类
|
|
public class HttpRequestHandler : MonoBehaviour
|
|
{
|
|
public static string httpIp ="http://192.168.101.210:8080";
|
|
|
|
// GET 请求
|
|
public IEnumerator GetRequest(string url, System.Action<string> onSuccess, System.Action<string> onError)
|
|
{
|
|
using (UnityWebRequest request = UnityWebRequest.Get(url))
|
|
{
|
|
yield return request.SendWebRequest();
|
|
|
|
if (request.isHttpError || request.isNetworkError)
|
|
{
|
|
onError?.Invoke(request.error);
|
|
}
|
|
else
|
|
{
|
|
// 请求成功,返回响应内容
|
|
onSuccess?.Invoke(request.downloadHandler.text);
|
|
}
|
|
}
|
|
}
|
|
|
|
// POST 请求
|
|
public IEnumerator PostRequest(string url, string jsonData, System.Action<string> onSuccess, System.Action<string> onError)
|
|
{
|
|
byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonData);
|
|
using (UnityWebRequest request = new UnityWebRequest(url, "POST"))
|
|
{
|
|
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
|
|
request.downloadHandler = new DownloadHandlerBuffer();
|
|
request.SetRequestHeader("Content-Type", "application/json");
|
|
|
|
yield return request.SendWebRequest();
|
|
|
|
if (request.isHttpError || request.isNetworkError)
|
|
{
|
|
onError?.Invoke(request.error);
|
|
}
|
|
else
|
|
{
|
|
// 请求成功,返回响应内容
|
|
onSuccess?.Invoke(request.downloadHandler.text);
|
|
}
|
|
}
|
|
}
|
|
}
|