HTTPRequestAsyncExtensions.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. using System;
  2. using System.Collections;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using Best.HTTP.Shared;
  6. using UnityEngine;
  7. #if WITH_UNITASK
  8. using Cysharp.Threading.Tasks;
  9. #endif
  10. namespace Best.HTTP
  11. {
  12. /// <summary>
  13. /// Represents an exception thrown during or as a result of a Task-based asynchronous HTTP operations.
  14. /// </summary>
  15. public sealed class AsyncHTTPException : Exception
  16. {
  17. /// <summary>
  18. /// Gets the status code of the server's response.
  19. /// </summary>
  20. public readonly int StatusCode;
  21. /// <summary>
  22. /// Gets the content sent by the server. This is usually an error page for 4xx or 5xx responses.
  23. /// </summary>
  24. public readonly string Content;
  25. public AsyncHTTPException(string message)
  26. : base(message)
  27. {
  28. }
  29. public AsyncHTTPException(string message, Exception innerException)
  30. : base(message, innerException)
  31. {
  32. }
  33. public AsyncHTTPException(int statusCode, string message, string content)
  34. :base(message)
  35. {
  36. this.StatusCode = statusCode;
  37. this.Content = content;
  38. }
  39. public override string ToString()
  40. {
  41. return string.Format("StatusCode: {0}, Message: {1}, Content: {2}, StackTrace: {3}", this.StatusCode, this.Message, this.Content, this.StackTrace);
  42. }
  43. }
  44. /// <summary>
  45. /// A collection of extension methods for working with HTTP requests asynchronously using <see cref="Task{TResult}"/>.
  46. /// </summary>
  47. public static class HTTPRequestAsyncExtensions
  48. {
  49. /// <summary>
  50. /// Asynchronously sends an HTTP request and retrieves the response as an <see cref="AssetBundle"/>.
  51. /// </summary>
  52. /// <param name="request">The <see cref="HTTPRequest"/> to send.</param>
  53. /// <param name="token">A cancellation token that can be used to cancel the operation.</param>
  54. /// <returns>
  55. /// A Task that represents the asynchronous operation. The Task will complete with the retrieved AssetBundle
  56. /// if the request succeeds. If the request fails or is canceled, the Task will complete with an exception.
  57. /// </returns>
  58. #if WITH_UNITASK
  59. public static UniTask<AssetBundle> GetAssetBundleAsync(this HTTPRequest request, CancellationToken token = default)
  60. #else
  61. public static Task<AssetBundle> GetAssetBundleAsync(this HTTPRequest request, CancellationToken token = default)
  62. #endif
  63. {
  64. return CreateTask<AssetBundle>(request, token,
  65. #if UNITY_2023_1_OR_NEWER
  66. async
  67. #endif
  68. (req, resp, tcs) =>
  69. {
  70. switch (req.State)
  71. {
  72. // The request finished without any problem.
  73. case HTTPRequestStates.Finished:
  74. if (resp.IsSuccess)
  75. {
  76. var bundleLoadOp = AssetBundle.LoadFromMemoryAsync(resp.Data);
  77. #if !UNITY_2023_1_OR_NEWER
  78. HTTPUpdateDelegator.Instance.StartCoroutine(BundleLoader(bundleLoadOp, tcs));
  79. #else
  80. await Awaitable.FromAsyncOperation(bundleLoadOp);
  81. tcs.TrySetResult(bundleLoadOp.assetBundle);
  82. #endif
  83. }
  84. else
  85. GenericResponseHandler<AssetBundle>(req, resp, tcs);
  86. break;
  87. default:
  88. GenericResponseHandler<AssetBundle>(req, resp, tcs);
  89. break;
  90. }
  91. });
  92. }
  93. #if !UNITY_2023_1_OR_NEWER
  94. #if WITH_UNITASK
  95. static IEnumerator BundleLoader(AssetBundleCreateRequest req, UniTaskCompletionSource<AssetBundle> tcs)
  96. #else
  97. static IEnumerator BundleLoader(AssetBundleCreateRequest req, TaskCompletionSource<AssetBundle> tcs)
  98. #endif
  99. {
  100. yield return req;
  101. tcs.TrySetResult(req.assetBundle);
  102. }
  103. #endif
  104. /// <summary>
  105. /// Asynchronously sends an HTTP request and retrieves the raw <see cref="HTTPResponse"/>.
  106. /// </summary>
  107. /// <remarks>
  108. /// This method is particularly useful when you want to access the raw response without any specific processing
  109. /// like converting the data into a string, texture, or other formats. It provides flexibility in handling
  110. /// the response for custom or advanced use cases.
  111. /// </remarks>
  112. /// <param name="request">The <see cref="HTTPRequest"/> to send.</param>
  113. /// <param name="token">An optional <see cref="CancellationToken"/> that can be used to cancel the operation.</param>
  114. /// <returns>
  115. /// A <see cref="Task{TResult}"/> that represents the asynchronous operation. The value of TResult is the raw <see cref="HTTPResponse"/>.
  116. /// If the request completes successfully, the task will return the HTTPResponse. If there's an error during the request or if
  117. /// the request gets canceled, the task will throw an exception, which can be caught and processed by the calling method.
  118. /// </returns>
  119. /// <exception cref="AsyncHTTPException">Thrown if there's an error in the request or if the server returns an error status code.</exception>
  120. #if WITH_UNITASK
  121. public static UniTask<HTTPResponse> GetHTTPResponseAsync(this HTTPRequest request, CancellationToken token = default)
  122. #else
  123. public static Task<HTTPResponse> GetHTTPResponseAsync(this HTTPRequest request, CancellationToken token = default)
  124. #endif
  125. {
  126. return CreateTask<HTTPResponse>(request, token, (req, resp, tcs) =>
  127. {
  128. switch (req.State)
  129. {
  130. // The request finished without any problem.
  131. case HTTPRequestStates.Finished:
  132. tcs.TrySetResult(resp);
  133. break;
  134. default:
  135. GenericResponseHandler<HTTPResponse>(req, resp, tcs);
  136. break;
  137. }
  138. });
  139. }
  140. /// <summary>
  141. /// Asynchronously sends an <see cref="HTTPRequest"/> and retrieves the response content as a <c>string</c>.
  142. /// </summary>
  143. /// <param name="request">The <see cref="HTTPRequest"/> to send.</param>
  144. /// <param name="token">A cancellation token that can be used to cancel the operation.</param>
  145. /// <returns>
  146. /// A Task that represents the asynchronous operation. The Task will complete with the retrieved <c>string</c> content
  147. /// if the request succeeds. If the request fails or is canceled, the Task will complete with an exception.
  148. /// </returns>
  149. #if WITH_UNITASK
  150. public static UniTask<string> GetAsStringAsync(this HTTPRequest request, CancellationToken token = default)
  151. #else
  152. public static Task<string> GetAsStringAsync(this HTTPRequest request, CancellationToken token = default)
  153. #endif
  154. {
  155. return CreateTask<string>(request, token, (req, resp, tcs) =>
  156. {
  157. switch (req.State)
  158. {
  159. // The request finished without any problem.
  160. case HTTPRequestStates.Finished:
  161. if (resp.IsSuccess)
  162. tcs.TrySetResult(resp.DataAsText);
  163. else
  164. GenericResponseHandler<string>(req, resp, tcs);
  165. break;
  166. default:
  167. GenericResponseHandler<string>(req, resp, tcs);
  168. break;
  169. }
  170. });
  171. }
  172. /// <summary>
  173. /// Asynchronously sends an <see cref="HTTPRequest"/> and retrieves the response content as a <see cref="Texture2D"/>.
  174. /// </summary>
  175. /// <param name="request">The <see cref="HTTPRequest"/> to send.</param>
  176. /// <param name="token">A cancellation token that can be used to cancel the operation.</param>
  177. /// <returns>
  178. /// A Task that represents the asynchronous operation. The Task will complete with the retrieved <see cref="Texture2D"/>
  179. /// if the request succeeds. If the request fails or is canceled, the Task will complete with an exception.
  180. /// </returns>
  181. #if WITH_UNITASK
  182. public static UniTask<Texture2D> GetAsTexture2DAsync(this HTTPRequest request, CancellationToken token = default)
  183. #else
  184. public static Task<Texture2D> GetAsTexture2DAsync(this HTTPRequest request, CancellationToken token = default)
  185. #endif
  186. {
  187. return CreateTask<Texture2D>(request, token, (req, resp, tcs) =>
  188. {
  189. switch (req.State)
  190. {
  191. // The request finished without any problem.
  192. case HTTPRequestStates.Finished:
  193. if (resp.IsSuccess)
  194. tcs.TrySetResult(resp.DataAsTexture2D);
  195. else
  196. GenericResponseHandler<Texture2D>(req, resp, tcs);
  197. break;
  198. default:
  199. GenericResponseHandler<Texture2D>(req, resp, tcs);
  200. break;
  201. }
  202. });
  203. }
  204. /// <summary>
  205. /// Asynchronously sends an <see cref="HTTPRequest"/> and retrieves the response content as a <c>byte[]</c>.
  206. /// </summary>
  207. /// <param name="request">The <see cref="HTTPRequest"/> to send.</param>
  208. /// <param name="token">A cancellation token that can be used to cancel the operation.</param>
  209. /// <returns>
  210. /// A Task that represents the asynchronous operation. The Task will complete with the retrieved <c>byte[]</c>
  211. /// if the request succeeds. If the request fails or is canceled, the Task will complete with an exception.
  212. /// </returns>
  213. #if WITH_UNITASK
  214. public static UniTask<byte[]> GetRawDataAsync(this HTTPRequest request, CancellationToken token = default)
  215. #else
  216. public static Task<byte[]> GetRawDataAsync(this HTTPRequest request, CancellationToken token = default)
  217. #endif
  218. {
  219. return CreateTask<byte[]>(request, token, (req, resp, tcs) =>
  220. {
  221. switch (req.State)
  222. {
  223. // The request finished without any problem.
  224. case HTTPRequestStates.Finished:
  225. if (resp.IsSuccess)
  226. tcs.TrySetResult(resp.Data);
  227. else
  228. GenericResponseHandler<byte[]>(req, resp, tcs);
  229. break;
  230. default:
  231. GenericResponseHandler<byte[]>(req, resp, tcs);
  232. break;
  233. }
  234. });
  235. }
  236. /// <summary>
  237. /// Asynchronously sends an <see cref="HTTPRequest"/> and deserializes the response content into an object of type T using JSON deserialization.
  238. /// </summary>
  239. /// <typeparam name="T">The type to deserialize the JSON content into.</typeparam>
  240. /// <param name="request">The <see cref="HTTPRequest"/> to send.</param>
  241. /// <param name="token">A cancellation token that can be used to cancel the operation.</param>
  242. /// <returns>
  243. /// A Task that represents the asynchronous operation. The Task will complete with the deserialized object
  244. /// if the request succeeds and the response content can be deserialized. If the request fails, is canceled, or
  245. /// the response cannot be deserialized, the Task will complete with an exception.
  246. /// </returns>
  247. #if WITH_UNITASK
  248. public static UniTask<T> GetFromJsonResultAsync<T>(this HTTPRequest request, CancellationToken token = default)
  249. #else
  250. public static Task<T> GetFromJsonResultAsync<T>(this HTTPRequest request, CancellationToken token = default)
  251. #endif
  252. {
  253. return HTTPRequestAsyncExtensions.CreateTask<T>(request, token, (req, resp, tcs) =>
  254. {
  255. switch (req.State)
  256. {
  257. // The request finished without any problem.
  258. case HTTPRequestStates.Finished:
  259. if (resp.IsSuccess)
  260. {
  261. try
  262. {
  263. tcs.TrySetResult(Best.HTTP.JSON.LitJson.JsonMapper.ToObject<T>(resp.DataAsText));
  264. }
  265. catch (Exception ex)
  266. {
  267. tcs.TrySetException(ex);
  268. }
  269. }
  270. else
  271. GenericResponseHandler<T>(req, resp, tcs);
  272. break;
  273. default:
  274. GenericResponseHandler<T>(req, resp, tcs);
  275. break;
  276. }
  277. });
  278. }
  279. [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
  280. #if WITH_UNITASK
  281. public static UniTask<T> CreateTask<T>(HTTPRequest request, CancellationToken token, Action<HTTPRequest, HTTPResponse, UniTaskCompletionSource<T>> callback)
  282. #else
  283. public static Task<T> CreateTask<T>(HTTPRequest request, CancellationToken token, Action<HTTPRequest, HTTPResponse, TaskCompletionSource<T>> callback)
  284. #endif
  285. {
  286. HTTPManager.Setup();
  287. #if WITH_UNITASK
  288. var tcs = new UniTaskCompletionSource<T>();
  289. #else
  290. var tcs = new TaskCompletionSource<T>();
  291. #endif
  292. request.Callback = (req, resp) =>
  293. {
  294. if (token.IsCancellationRequested)
  295. tcs.TrySetCanceled();
  296. else
  297. callback(req, resp, tcs);
  298. };
  299. if (token.CanBeCanceled)
  300. token.Register((state) => (state as HTTPRequest)?.Abort(), request);
  301. if (request.State == HTTPRequestStates.Initial)
  302. request.Send();
  303. return tcs.Task;
  304. }
  305. #if WITH_UNITASK
  306. public static void GenericResponseHandler<T>(HTTPRequest req, HTTPResponse resp, UniTaskCompletionSource<T> tcs)
  307. #else
  308. public static void GenericResponseHandler<T>(HTTPRequest req, HTTPResponse resp, TaskCompletionSource<T> tcs)
  309. #endif
  310. {
  311. switch (req.State)
  312. {
  313. // The request finished without any problem.
  314. case HTTPRequestStates.Finished:
  315. if (!resp.IsSuccess)
  316. tcs.TrySetException(CreateException($"Request finished Successfully, but the server sent an error ({resp.StatusCode} - '{resp.Message}').", resp));
  317. break;
  318. // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
  319. case HTTPRequestStates.Error:
  320. Log(req, $"Request Finished with Error! {req.Exception?.Message} - {req.Exception?.StackTrace}");
  321. tcs.TrySetException(CreateException("No Exception", null, req.Exception));
  322. break;
  323. // The request aborted, initiated by the user.
  324. case HTTPRequestStates.Aborted:
  325. Log(req, "Request Aborted!");
  326. tcs.TrySetCanceled();
  327. break;
  328. // Connecting to the server is timed out.
  329. case HTTPRequestStates.ConnectionTimedOut:
  330. Log(req, "Connection Timed Out!");
  331. tcs.TrySetException(CreateException("Connection Timed Out!"));
  332. break;
  333. // The request didn't finished in the given time.
  334. case HTTPRequestStates.TimedOut:
  335. Log(req, "Processing the request Timed Out!");
  336. tcs.TrySetException(CreateException("Processing the request Timed Out!"));
  337. break;
  338. }
  339. }
  340. [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
  341. public static void Log(HTTPRequest request, string str)
  342. {
  343. HTTPManager.Logger.Verbose(nameof(HTTPRequestAsyncExtensions), str, request.Context);
  344. }
  345. [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
  346. public static Exception CreateException(string errorMessage, HTTPResponse resp = null, Exception ex = null)
  347. {
  348. if (resp != null)
  349. return new AsyncHTTPException(resp.StatusCode, resp.Message, resp.DataAsText);
  350. else if (ex != null)
  351. return new AsyncHTTPException(ex.Message, ex);
  352. else
  353. return new AsyncHTTPException(errorMessage);
  354. }
  355. }
  356. }