using System; using System.Collections; using System.Collections.Generic; using System.Text; using UnityEngine.Networking; using UnityEngine; namespace EZXR.Glass.Network.Http { /** * \~english * Network request tool class(Implement based on UnityWebRequest @see) * * \~chinese * 网络请求工具类(底层基于Unity的UnityWebRequest @see实现) */ public class HttpClient { private static readonly HttpClient Instance = new HttpClient(); private HttpClient() { } /** * \~english * @brief Send asynchronous request * * @param httpRequest httpRequest * * @param responseHandler Callback function returned by request * * \~chinese * @brief 发送异步请求 * * @param httpRequest httpRequest * * @param responseHandler 请求返回的回调函数 */ public static void SendRequest(HttpRequest httpRequest, Action responseHandler) { HttpTool.Instance.StartCoroutine (HttpClient.Instance.Send(httpRequest, responseHandler)); } public IEnumerator Send(HttpRequest httpRequest, Action onComplete) { // Employing `using` will ensure that the UnityWebRequest is properly cleaned in case of uncaught exceptions using (var www = new UnityWebRequest (httpRequest.url, httpRequest.method.ToString())) { www.timeout = httpRequest.timeout; if (httpRequest.requestBody != null) { UploadHandler uploader = new UploadHandlerRaw (httpRequest.requestBody.Body ()); uploader.contentType = httpRequest.requestBody.ContentType (); www.uploadHandler = uploader; } if (httpRequest.Headers() != null) { foreach (KeyValuePair header in httpRequest.Headers()) { www.SetRequestHeader (header.Key, header.Value); } } www.downloadHandler = new DownloadHandlerBuffer (); yield return www.SendWebRequest (); HttpResponse response; if (www.isNetworkError || www.isHttpError) { response = new HttpResponse(www.error); } else { response = new HttpResponse(www.responseCode, www.downloadHandler.text); } onComplete(response); } } } }