123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- 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<https://docs.unity3d.com/Manual/UnityWebRequest.html>)
- *
- * \~chinese
- * 网络请求工具类(底层基于Unity的UnityWebRequest @see<https://docs.unity3d.com/Manual/UnityWebRequest.html>实现)
- */
- 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<HttpResponse> responseHandler)
- {
- HttpTool.Instance.StartCoroutine (HttpClient.Instance.Send(httpRequest, responseHandler));
- }
- public IEnumerator Send(HttpRequest httpRequest, Action<HttpResponse> 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<string, string> 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);
- }
- }
- }
- }
|