12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- 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<string> successAction,
- Action<UnityWebRequest.Result> errorAction)
- {
- return _http_request(url, "POST", postData, successAction, errorAction);
- }
- public static IEnumerator HttpGet(string url, Action<string> successAction,
- Action<UnityWebRequest.Result> errorAction)
- {
- return _http_request(url, "GET", null, successAction, errorAction);
- }
- [CanBeNull]
- private static IEnumerator _http_request(string url, string method,
- string postData,
- Action<string> responseAction, Action<UnityWebRequest.Result> 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();
- }
- }
- }
- }
- }
|