AsyncHttpClient.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. using MediaBrowser.Model.Logging;
  2. using MediaBrowser.Model.Net;
  3. using System;
  4. using System.IO;
  5. using System.Net.Http;
  6. using System.Net.Http.Headers;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. namespace MediaBrowser.ApiInteraction
  11. {
  12. /// <summary>
  13. /// Class AsyncHttpClient
  14. /// </summary>
  15. public class AsyncHttpClient : IAsyncHttpClient
  16. {
  17. /// <summary>
  18. /// Gets or sets the HTTP client.
  19. /// </summary>
  20. /// <value>The HTTP client.</value>
  21. private HttpClient HttpClient { get; set; }
  22. /// <summary>
  23. /// Initializes a new instance of the <see cref="ApiClient" /> class.
  24. /// </summary>
  25. public AsyncHttpClient(HttpMessageHandler handler)
  26. {
  27. HttpClient = new HttpClient(handler);
  28. }
  29. /// <summary>
  30. /// Initializes a new instance of the <see cref="ApiClient" /> class.
  31. /// </summary>
  32. public AsyncHttpClient()
  33. {
  34. HttpClient = new HttpClient();
  35. }
  36. /// <summary>
  37. /// Gets the stream async.
  38. /// </summary>
  39. /// <param name="url">The URL.</param>
  40. /// <param name="logger">The logger.</param>
  41. /// <param name="cancellationToken">The cancellation token.</param>
  42. /// <returns>Task{Stream}.</returns>
  43. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  44. public async Task<Stream> GetStreamAsync(string url, ILogger logger, CancellationToken cancellationToken)
  45. {
  46. cancellationToken.ThrowIfCancellationRequested();
  47. logger.Debug("Sending Http Get to {0}", url);
  48. try
  49. {
  50. var msg = await HttpClient.GetAsync(url, cancellationToken).ConfigureAwait(false);
  51. EnsureSuccessStatusCode(msg);
  52. return await msg.Content.ReadAsStreamAsync().ConfigureAwait(false);
  53. }
  54. catch (HttpRequestException ex)
  55. {
  56. logger.ErrorException("Error getting response from " + url, ex);
  57. throw new HttpException(ex.Message, ex);
  58. }
  59. catch (OperationCanceledException ex)
  60. {
  61. throw GetCancellationException(url, cancellationToken, ex, logger);
  62. }
  63. catch (Exception ex)
  64. {
  65. logger.ErrorException("Error requesting {0}", ex, url);
  66. throw;
  67. }
  68. }
  69. /// <summary>
  70. /// Posts the async.
  71. /// </summary>
  72. /// <param name="url">The URL.</param>
  73. /// <param name="contentType">Type of the content.</param>
  74. /// <param name="postContent">Content of the post.</param>
  75. /// <param name="logger">The logger.</param>
  76. /// <param name="cancellationToken">The cancellation token.</param>
  77. /// <returns>Task{Stream}.</returns>
  78. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  79. public async Task<Stream> PostAsync(string url, string contentType, string postContent, ILogger logger, CancellationToken cancellationToken)
  80. {
  81. logger.Debug("Sending Http Post to {0}", url);
  82. var content = new StringContent(postContent, Encoding.UTF8, contentType);
  83. try
  84. {
  85. var msg = await HttpClient.PostAsync(url, content).ConfigureAwait(false);
  86. EnsureSuccessStatusCode(msg);
  87. return await msg.Content.ReadAsStreamAsync().ConfigureAwait(false);
  88. }
  89. catch (HttpRequestException ex)
  90. {
  91. logger.ErrorException("Error getting response from " + url, ex);
  92. throw new HttpException(ex.Message, ex);
  93. }
  94. catch (OperationCanceledException ex)
  95. {
  96. throw GetCancellationException(url, cancellationToken, ex, logger);
  97. }
  98. catch (Exception ex)
  99. {
  100. logger.ErrorException("Error posting {0}", ex, url);
  101. throw;
  102. }
  103. }
  104. /// <summary>
  105. /// Deletes the async.
  106. /// </summary>
  107. /// <param name="url">The URL.</param>
  108. /// <param name="logger">The logger.</param>
  109. /// <param name="cancellationToken">The cancellation token.</param>
  110. /// <returns>Task.</returns>
  111. public async Task DeleteAsync(string url, ILogger logger, CancellationToken cancellationToken)
  112. {
  113. cancellationToken.ThrowIfCancellationRequested();
  114. logger.Debug("Sending Http Delete to {0}", url);
  115. try
  116. {
  117. using (var msg = await HttpClient.DeleteAsync(url, cancellationToken).ConfigureAwait(false))
  118. {
  119. EnsureSuccessStatusCode(msg);
  120. }
  121. }
  122. catch (HttpRequestException ex)
  123. {
  124. logger.ErrorException("Error getting response from " + url, ex);
  125. throw new HttpException(ex.Message, ex);
  126. }
  127. catch (OperationCanceledException ex)
  128. {
  129. throw GetCancellationException(url, cancellationToken, ex, logger);
  130. }
  131. catch (Exception ex)
  132. {
  133. logger.ErrorException("Error requesting {0}", ex, url);
  134. throw;
  135. }
  136. }
  137. /// <summary>
  138. /// Throws the cancellation exception.
  139. /// </summary>
  140. /// <param name="url">The URL.</param>
  141. /// <param name="cancellationToken">The cancellation token.</param>
  142. /// <param name="exception">The exception.</param>
  143. /// <param name="logger">The logger.</param>
  144. /// <returns>Exception.</returns>
  145. private Exception GetCancellationException(string url, CancellationToken cancellationToken, OperationCanceledException exception, ILogger logger)
  146. {
  147. // If the HttpClient's timeout is reached, it will cancel the Task internally
  148. if (!cancellationToken.IsCancellationRequested)
  149. {
  150. var msg = string.Format("Connection to {0} timed out", url);
  151. logger.Error(msg);
  152. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  153. return new HttpException(msg, exception) { IsTimedOut = true };
  154. }
  155. return exception;
  156. }
  157. /// <summary>
  158. /// Ensures the success status code.
  159. /// </summary>
  160. /// <param name="response">The response.</param>
  161. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  162. private void EnsureSuccessStatusCode(HttpResponseMessage response)
  163. {
  164. if (!response.IsSuccessStatusCode)
  165. {
  166. throw new HttpException(response.ReasonPhrase) { StatusCode = response.StatusCode };
  167. }
  168. }
  169. /// <summary>
  170. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  171. /// </summary>
  172. public void Dispose()
  173. {
  174. Dispose(true);
  175. }
  176. /// <summary>
  177. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  178. /// </summary>
  179. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  180. protected virtual void Dispose(bool disposing)
  181. {
  182. if (disposing)
  183. {
  184. HttpClient.Dispose();
  185. }
  186. }
  187. /// <summary>
  188. /// Sets the authorization header that should be supplied on every request
  189. /// </summary>
  190. /// <param name="header">The header.</param>
  191. /// <exception cref="System.NotImplementedException"></exception>
  192. public void SetAuthorizationHeader(string header)
  193. {
  194. if (string.IsNullOrEmpty(header))
  195. {
  196. HttpClient.DefaultRequestHeaders.Remove("Authorization");
  197. }
  198. else
  199. {
  200. HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("MediaBrowser", header);
  201. }
  202. }
  203. }
  204. }