HttpClient.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using UnityEngine.Networking;
  6. using UnityEngine;
  7. namespace EZXR.Glass.Network.Http
  8. {
  9. /**
  10. * \~english
  11. * Network request tool class(Implement based on UnityWebRequest @see<https://docs.unity3d.com/Manual/UnityWebRequest.html>)
  12. *
  13. * \~chinese
  14. * 网络请求工具类(底层基于Unity的UnityWebRequest @see<https://docs.unity3d.com/Manual/UnityWebRequest.html>实现)
  15. */
  16. public class HttpClient
  17. {
  18. private static readonly HttpClient Instance = new HttpClient();
  19. private HttpClient()
  20. {
  21. }
  22. /**
  23. * \~english
  24. * @brief Send asynchronous request
  25. *
  26. * @param httpRequest httpRequest
  27. *
  28. * @param responseHandler Callback function returned by request
  29. *
  30. * \~chinese
  31. * @brief 发送异步请求
  32. *
  33. * @param httpRequest httpRequest
  34. *
  35. * @param responseHandler 请求返回的回调函数
  36. */
  37. public static void SendRequest(HttpRequest httpRequest, Action<HttpResponse> responseHandler)
  38. {
  39. HttpTool.Instance.StartCoroutine (HttpClient.Instance.Send(httpRequest, responseHandler));
  40. }
  41. public IEnumerator Send(HttpRequest httpRequest, Action<HttpResponse> onComplete) {
  42. // Employing `using` will ensure that the UnityWebRequest is properly cleaned in case of uncaught exceptions
  43. using (var www = new UnityWebRequest (httpRequest.url, httpRequest.method.ToString())) {
  44. www.timeout = httpRequest.timeout;
  45. if (httpRequest.requestBody != null) {
  46. UploadHandler uploader = new UploadHandlerRaw (httpRequest.requestBody.Body ());
  47. uploader.contentType = httpRequest.requestBody.ContentType ();
  48. www.uploadHandler = uploader;
  49. }
  50. if (httpRequest.Headers() != null) {
  51. foreach (KeyValuePair<string, string> header in httpRequest.Headers()) {
  52. www.SetRequestHeader (header.Key, header.Value);
  53. }
  54. }
  55. www.downloadHandler = new DownloadHandlerBuffer ();
  56. yield return www.SendWebRequest ();
  57. HttpResponse response;
  58. if (www.isNetworkError || www.isHttpError) {
  59. response = new HttpResponse(www.error);
  60. } else {
  61. response = new HttpResponse(www.responseCode, www.downloadHandler.text);
  62. }
  63. onComplete(response);
  64. }
  65. }
  66. }
  67. }