| | |
| | | using System.Collections; |
| | | using System.Collections.Generic; |
| | | using UnityEngine; |
| | | using UnityEngine.Networking; |
| | | using System; |
| | | using System.Net; |
| | | using System.Text; |
| | | using System.IO; |
| | | using System.Net.Security; |
| | | using System.Security.Cryptography.X509Certificates; |
| | | using Cysharp.Threading.Tasks; |
| | | |
| | | |
| | | public class HttpBehaviour : MonoBehaviour |
| | | public class HttpBehaviour : MonoBehaviour |
| | | { |
| | | |
| | | string url; |
| | |
| | | behaviour.Begin(_url, _method, _content, _contentType, _retry, _result); |
| | | } |
| | | |
| | | /// <summary> |
| | | /// Create 的异步版本,使用 UnityWebRequest 实现,支持所有平台(含 WebGL)。 |
| | | /// </summary> |
| | | public static async UniTask<(bool ok, string message)> CreateAsync(string _url, string _method, string _content, string _contentType, int _retry = 3, Action<bool, string> _result = null) |
| | | { |
| | | bool ok = false; |
| | | string message = string.Empty; |
| | | |
| | | for (int attempt = 0; attempt <= _retry; attempt++) |
| | | { |
| | | UnityWebRequest www; |
| | | if (_method == "POST") |
| | | { |
| | | var bodyRaw = Encoding.UTF8.GetBytes(_content); |
| | | www = new UnityWebRequest(_url, "POST"); |
| | | www.uploadHandler = new UploadHandlerRaw(bodyRaw); |
| | | www.downloadHandler = new DownloadHandlerBuffer(); |
| | | www.SetRequestHeader("Content-Type", _contentType); |
| | | } |
| | | else |
| | | { |
| | | www = UnityWebRequest.Get(_url); |
| | | www.SetRequestHeader("Content-Type", _contentType); |
| | | } |
| | | |
| | | using (www) |
| | | { |
| | | await www.SendWebRequest(); |
| | | ok = www.result == UnityWebRequest.Result.Success; |
| | | message = ok ? www.downloadHandler.text : www.error; |
| | | } |
| | | |
| | | if (ok) |
| | | { |
| | | ConnectAllTimes = 0; |
| | | break; |
| | | } |
| | | |
| | | ConnectAllTimes++; |
| | | Debug.LogWarning($"[HttpBehaviour] CreateAsync failed (attempt {attempt + 1}/{_retry + 1}): {message} url={_url}"); |
| | | } |
| | | |
| | | _result?.Invoke(ok, message); |
| | | return (ok, message); |
| | | } |
| | | |
| | | void Begin(string _url, string _method, string _content, string _contentType, int _retry = 3, Action<bool, string> _result = null) |
| | | { |
| | | this.url = _url; |