这里写自定义目录标题
UnityWebRequest 简单post get 请求
简单的请求,有需要可拓展
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.Text;
using System;
using LitJson;
using SadTools;
using Http.Model;
using UnityEditor.PackageManager.Requests;
public class HttpClientVR : UnitySingleton<HttpClientVR>
{
private static string TAG = "[HttpClient] ";
//服务器地址
private static string url = "https://**************/server/";
private void Start()
{
}
/// <summary>
/// Post请求
/// </summary>
/// <param name="req">请求体</param>
/// <param name="callback">接口回调</param>
public void Post(BaseRequestModel req, Action<string> callback)
{
StartCoroutine(I_RequestByJsonBodyPost(url + req.type, JsonMapper.ToJson(req), callback));
}
/// <summary>
/// 接口请求携程
/// </summary>
private static IEnumerator I_RequestByJsonBodyPost(string url, string json, Action<string> callback)
{
Debug.Log(TAG + url + "\n" + "RequestModel : " + json);
var uwr = new UnityWebRequest(url, "POST");
byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json);
uwr.uploadHandler = (UploadHandler)new UploadHandlerRaw(jsonToSend);
uwr.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
uwr.certificateHandler = new WebRequestCertificate();
uwr.SetRequestHeader("Content-Type", "application/json");
yield return uwr.SendWebRequest();
if (uwr.isDone)
{
Debug.Log(uwr.downloadHandler.text);
string data = uwr.downloadHandler.text;
if (data != null && !data.Equals(""))
{
callback(data);
}
else
{
Debug.LogError("接口请求失败");
}
}
}
/// <summary>
/// Get请求
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="callback">接口回调</param>
public void Get(string url, Action<string> callback)
{
StartCoroutine(I_RequestGET(url, callback));
}
/// <summary>
/// 接口请求携程
/// </summary>
private static IEnumerator I_RequestGET(string url, Action<string> callback)
{
UnityWebRequest request = UnityWebRequest.Get(url);
request.certificateHandler = new WebRequestCertificate();
yield return request.SendWebRequest();
Debug.Log(request.error);
Debug.Log(request.responseCode);
Debug.Log(request.downloadHandler.text);
callback?.Invoke(request.downloadHandler.text);
}
}