using System; using System.Collections; using System.Net.Http; using System.Text; using JetBrains.Annotations; using UnityEngine; using UnityEngine.Networking; namespace Plugins.CxShine.net { public class CxHttp { public static IEnumerator HttpPost(string url, string postData, Action successAction, Action errorAction) { return _http_request(url, "POST", postData, successAction, errorAction); } public static IEnumerator HttpGet(string url, Action successAction, Action errorAction) { return _http_request(url, "GET", null, successAction, errorAction); } [CanBeNull] private static IEnumerator _http_request(string url, string method, string postData, Action responseAction, Action errorAction) { using (var uwr = new UnityWebRequest(url, method)) { // add upload data if POST if ("POST" == method) { var postBytes = Encoding.UTF8.GetBytes(postData); uwr.uploadHandler = new UploadHandlerRaw(postBytes); } uwr.timeout = 5; uwr.downloadHandler = new DownloadHandlerBuffer(); uwr.SetRequestHeader("Content-Type", "application/json"); yield return uwr.SendWebRequest(); switch (uwr.result) { case UnityWebRequest.Result.ConnectionError: case UnityWebRequest.Result.ProtocolError: case UnityWebRequest.Result.DataProcessingError: Debug.Log(uwr.error); errorAction?.Invoke(uwr.result); break; case UnityWebRequest.Result.Success: { var responseText = uwr.downloadHandler.text; // Debug.Log("Status Code:" + uwr.responseCode + " request.url:" + // uwr.uri + "request.data:" + postData + // "request.resp:" + responseText); responseAction?.Invoke(responseText); break; } case UnityWebRequest.Result.InProgress: break; default: throw new ArgumentOutOfRangeException(); } } } } }