HttpClientManager.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. using System.Net.Sockets;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Common.IO;
  5. using MediaBrowser.Common.Net;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Net;
  8. using System;
  9. using System.Collections.Concurrent;
  10. using System.Collections.Generic;
  11. using System.Collections.Specialized;
  12. using System.Globalization;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Net;
  16. using System.Net.Cache;
  17. using System.Text;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. using CommonIO;
  21. namespace MediaBrowser.Common.Implementations.HttpClientManager
  22. {
  23. /// <summary>
  24. /// Class HttpClientManager
  25. /// </summary>
  26. public class HttpClientManager : IHttpClient
  27. {
  28. /// <summary>
  29. /// When one request to a host times out, we'll ban all other requests for this period of time, to prevent scans from stalling
  30. /// </summary>
  31. private const int TimeoutSeconds = 30;
  32. /// <summary>
  33. /// The _logger
  34. /// </summary>
  35. private readonly ILogger _logger;
  36. /// <summary>
  37. /// The _app paths
  38. /// </summary>
  39. private readonly IApplicationPaths _appPaths;
  40. private readonly IFileSystem _fileSystem;
  41. /// <summary>
  42. /// Initializes a new instance of the <see cref="HttpClientManager" /> class.
  43. /// </summary>
  44. /// <param name="appPaths">The app paths.</param>
  45. /// <param name="logger">The logger.</param>
  46. /// <param name="fileSystem">The file system.</param>
  47. /// <exception cref="System.ArgumentNullException">appPaths
  48. /// or
  49. /// logger</exception>
  50. public HttpClientManager(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem)
  51. {
  52. if (appPaths == null)
  53. {
  54. throw new ArgumentNullException("appPaths");
  55. }
  56. if (logger == null)
  57. {
  58. throw new ArgumentNullException("logger");
  59. }
  60. _logger = logger;
  61. _fileSystem = fileSystem;
  62. _appPaths = appPaths;
  63. // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
  64. ServicePointManager.Expect100Continue = false;
  65. // Trakt requests sometimes fail without this
  66. ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
  67. }
  68. /// <summary>
  69. /// Holds a dictionary of http clients by host. Use GetHttpClient(host) to retrieve or create a client for web requests.
  70. /// DON'T dispose it after use.
  71. /// </summary>
  72. /// <value>The HTTP clients.</value>
  73. private readonly ConcurrentDictionary<string, HttpClientInfo> _httpClients = new ConcurrentDictionary<string, HttpClientInfo>();
  74. /// <summary>
  75. /// Gets
  76. /// </summary>
  77. /// <param name="host">The host.</param>
  78. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  79. /// <returns>HttpClient.</returns>
  80. /// <exception cref="System.ArgumentNullException">host</exception>
  81. private HttpClientInfo GetHttpClient(string host, bool enableHttpCompression)
  82. {
  83. if (string.IsNullOrEmpty(host))
  84. {
  85. throw new ArgumentNullException("host");
  86. }
  87. HttpClientInfo client;
  88. var key = host + enableHttpCompression;
  89. if (!_httpClients.TryGetValue(key, out client))
  90. {
  91. client = new HttpClientInfo();
  92. _httpClients.TryAdd(key, client);
  93. }
  94. return client;
  95. }
  96. private WebRequest CreateWebRequest(string url)
  97. {
  98. try
  99. {
  100. return WebRequest.Create(url);
  101. }
  102. catch (NotSupportedException)
  103. {
  104. //Webrequest creation does fail on MONO randomly when using WebRequest.Create
  105. //the issue occurs in the GetCreator method here: http://www.oschina.net/code/explore/mono-2.8.1/mcs/class/System/System.Net/WebRequest.cs
  106. var type = Type.GetType("System.Net.HttpRequestCreator, System, Version=4.0.0.0,Culture=neutral, PublicKeyToken=b77a5c561934e089");
  107. var creator = Activator.CreateInstance(type, nonPublic: true) as IWebRequestCreate;
  108. return creator.Create(new Uri(url)) as HttpWebRequest;
  109. }
  110. }
  111. private void AddIpv4Option(HttpWebRequest request, HttpRequestOptions options)
  112. {
  113. if (!options.PreferIpv4)
  114. {
  115. return;
  116. }
  117. request.ServicePoint.BindIPEndPointDelegate = (servicePount, remoteEndPoint, retryCount) =>
  118. {
  119. if (remoteEndPoint.AddressFamily == AddressFamily.InterNetwork)
  120. {
  121. return new IPEndPoint(IPAddress.Any, 0);
  122. }
  123. throw new InvalidOperationException("no IPv4 address");
  124. };
  125. }
  126. private WebRequest GetRequest(HttpRequestOptions options, string method, bool enableHttpCompression)
  127. {
  128. var request = CreateWebRequest(options.Url);
  129. var httpWebRequest = request as HttpWebRequest;
  130. if (httpWebRequest != null)
  131. {
  132. AddIpv4Option(httpWebRequest, options);
  133. AddRequestHeaders(httpWebRequest, options);
  134. httpWebRequest.AutomaticDecompression = enableHttpCompression ? DecompressionMethods.Deflate : DecompressionMethods.None;
  135. }
  136. request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
  137. if (httpWebRequest != null)
  138. {
  139. if (options.EnableKeepAlive)
  140. {
  141. httpWebRequest.KeepAlive = true;
  142. }
  143. }
  144. request.Method = method;
  145. request.Timeout = options.TimeoutMs;
  146. if (httpWebRequest != null)
  147. {
  148. if (!string.IsNullOrEmpty(options.Host))
  149. {
  150. httpWebRequest.Host = options.Host;
  151. }
  152. if (!string.IsNullOrEmpty(options.Referer))
  153. {
  154. httpWebRequest.Referer = options.Referer;
  155. }
  156. }
  157. return request;
  158. }
  159. private void AddRequestHeaders(HttpWebRequest request, HttpRequestOptions options)
  160. {
  161. foreach (var header in options.RequestHeaders.ToList())
  162. {
  163. if (string.Equals(header.Key, "Accept", StringComparison.OrdinalIgnoreCase))
  164. {
  165. request.Accept = header.Value;
  166. }
  167. else if (string.Equals(header.Key, "User-Agent", StringComparison.OrdinalIgnoreCase))
  168. {
  169. request.UserAgent = header.Value;
  170. }
  171. else
  172. {
  173. request.Headers.Set(header.Key, header.Value);
  174. }
  175. }
  176. }
  177. /// <summary>
  178. /// Gets the response internal.
  179. /// </summary>
  180. /// <param name="options">The options.</param>
  181. /// <returns>Task{HttpResponseInfo}.</returns>
  182. public Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
  183. {
  184. return SendAsync(options, "GET");
  185. }
  186. /// <summary>
  187. /// Performs a GET request and returns the resulting stream
  188. /// </summary>
  189. /// <param name="options">The options.</param>
  190. /// <returns>Task{Stream}.</returns>
  191. public async Task<Stream> Get(HttpRequestOptions options)
  192. {
  193. var response = await GetResponse(options).ConfigureAwait(false);
  194. return response.Content;
  195. }
  196. /// <summary>
  197. /// Performs a GET request and returns the resulting stream
  198. /// </summary>
  199. /// <param name="url">The URL.</param>
  200. /// <param name="resourcePool">The resource pool.</param>
  201. /// <param name="cancellationToken">The cancellation token.</param>
  202. /// <returns>Task{Stream}.</returns>
  203. public Task<Stream> Get(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  204. {
  205. return Get(new HttpRequestOptions
  206. {
  207. Url = url,
  208. ResourcePool = resourcePool,
  209. CancellationToken = cancellationToken,
  210. });
  211. }
  212. /// <summary>
  213. /// Gets the specified URL.
  214. /// </summary>
  215. /// <param name="url">The URL.</param>
  216. /// <param name="cancellationToken">The cancellation token.</param>
  217. /// <returns>Task{Stream}.</returns>
  218. public Task<Stream> Get(string url, CancellationToken cancellationToken)
  219. {
  220. return Get(url, null, cancellationToken);
  221. }
  222. /// <summary>
  223. /// send as an asynchronous operation.
  224. /// </summary>
  225. /// <param name="options">The options.</param>
  226. /// <param name="httpMethod">The HTTP method.</param>
  227. /// <returns>Task{HttpResponseInfo}.</returns>
  228. /// <exception cref="HttpException">
  229. /// </exception>
  230. public async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod)
  231. {
  232. HttpResponseInfo response;
  233. if (options.CacheMode == CacheMode.None)
  234. {
  235. response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  236. return response;
  237. }
  238. var url = options.Url;
  239. var urlHash = url.ToLower().GetMD5().ToString("N");
  240. var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash);
  241. response = await GetCachedResponse(responseCachePath, options.CacheLength, url).ConfigureAwait(false);
  242. if (response != null)
  243. {
  244. return response;
  245. }
  246. response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  247. if (response.StatusCode == HttpStatusCode.OK)
  248. {
  249. await CacheResponse(response, responseCachePath).ConfigureAwait(false);
  250. }
  251. return response;
  252. }
  253. private async Task<HttpResponseInfo> GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url)
  254. {
  255. try
  256. {
  257. if (_fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow)
  258. {
  259. using (var stream = _fileSystem.GetFileStream(responseCachePath, FileMode.Open, FileAccess.Read, FileShare.Read, true))
  260. {
  261. var memoryStream = new MemoryStream();
  262. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  263. memoryStream.Position = 0;
  264. return new HttpResponseInfo
  265. {
  266. ResponseUrl = url,
  267. Content = memoryStream,
  268. StatusCode = HttpStatusCode.OK,
  269. Headers = new NameValueCollection(),
  270. ContentLength = memoryStream.Length
  271. };
  272. }
  273. }
  274. }
  275. catch (FileNotFoundException)
  276. {
  277. }
  278. catch (DirectoryNotFoundException)
  279. {
  280. }
  281. return null;
  282. }
  283. private async Task CacheResponse(HttpResponseInfo response, string responseCachePath)
  284. {
  285. _fileSystem.CreateDirectory(Path.GetDirectoryName(responseCachePath));
  286. using (var responseStream = response.Content)
  287. {
  288. var memoryStream = new MemoryStream();
  289. await responseStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  290. memoryStream.Position = 0;
  291. using (var fileStream = _fileSystem.GetFileStream(responseCachePath, FileMode.Create, FileAccess.Write, FileShare.None, true))
  292. {
  293. await memoryStream.CopyToAsync(fileStream).ConfigureAwait(false);
  294. memoryStream.Position = 0;
  295. response.Content = memoryStream;
  296. }
  297. }
  298. }
  299. private async Task<HttpResponseInfo> SendAsyncInternal(HttpRequestOptions options, string httpMethod)
  300. {
  301. ValidateParams(options);
  302. options.CancellationToken.ThrowIfCancellationRequested();
  303. var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
  304. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  305. {
  306. throw new HttpException(string.Format("Cancelling connection to {0} due to a previous timeout.", options.Url))
  307. {
  308. IsTimedOut = true
  309. };
  310. }
  311. var httpWebRequest = GetRequest(options, httpMethod, options.EnableHttpCompression);
  312. if (options.RequestContentBytes != null ||
  313. !string.IsNullOrEmpty(options.RequestContent) ||
  314. string.Equals(httpMethod, "post", StringComparison.OrdinalIgnoreCase))
  315. {
  316. var bytes = options.RequestContentBytes ??
  317. Encoding.UTF8.GetBytes(options.RequestContent ?? string.Empty);
  318. httpWebRequest.ContentType = options.RequestContentType ?? "application/x-www-form-urlencoded";
  319. httpWebRequest.ContentLength = bytes.Length;
  320. httpWebRequest.GetRequestStream().Write(bytes, 0, bytes.Length);
  321. }
  322. if (options.ResourcePool != null)
  323. {
  324. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  325. }
  326. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  327. {
  328. if (options.ResourcePool != null)
  329. {
  330. options.ResourcePool.Release();
  331. }
  332. throw new HttpException(string.Format("Connection to {0} timed out", options.Url)) { IsTimedOut = true };
  333. }
  334. if (options.LogRequest)
  335. {
  336. _logger.Info("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url);
  337. }
  338. try
  339. {
  340. options.CancellationToken.ThrowIfCancellationRequested();
  341. if (!options.BufferContent)
  342. {
  343. var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false);
  344. var httpResponse = (HttpWebResponse)response;
  345. EnsureSuccessStatusCode(client, httpResponse, options);
  346. options.CancellationToken.ThrowIfCancellationRequested();
  347. return GetResponseInfo(httpResponse, httpResponse.GetResponseStream(), GetContentLength(httpResponse), httpResponse);
  348. }
  349. using (var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false))
  350. {
  351. var httpResponse = (HttpWebResponse)response;
  352. EnsureSuccessStatusCode(client, httpResponse, options);
  353. options.CancellationToken.ThrowIfCancellationRequested();
  354. using (var stream = httpResponse.GetResponseStream())
  355. {
  356. var memoryStream = new MemoryStream();
  357. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  358. memoryStream.Position = 0;
  359. return GetResponseInfo(httpResponse, memoryStream, memoryStream.Length, null);
  360. }
  361. }
  362. }
  363. catch (OperationCanceledException ex)
  364. {
  365. throw GetCancellationException(options, client, options.CancellationToken, ex);
  366. }
  367. catch (Exception ex)
  368. {
  369. throw GetException(ex, options, client);
  370. }
  371. finally
  372. {
  373. if (options.ResourcePool != null)
  374. {
  375. options.ResourcePool.Release();
  376. }
  377. }
  378. }
  379. private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, Stream content, long? contentLength, IDisposable disposable)
  380. {
  381. return new HttpResponseInfo(disposable)
  382. {
  383. Content = content,
  384. StatusCode = httpResponse.StatusCode,
  385. ContentType = httpResponse.ContentType,
  386. Headers = new NameValueCollection(httpResponse.Headers),
  387. ContentLength = contentLength,
  388. ResponseUrl = httpResponse.ResponseUri.ToString()
  389. };
  390. }
  391. private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, string tempFile, long? contentLength)
  392. {
  393. return new HttpResponseInfo
  394. {
  395. TempFilePath = tempFile,
  396. StatusCode = httpResponse.StatusCode,
  397. ContentType = httpResponse.ContentType,
  398. Headers = httpResponse.Headers,
  399. ContentLength = contentLength
  400. };
  401. }
  402. public Task<HttpResponseInfo> Post(HttpRequestOptions options)
  403. {
  404. return SendAsync(options, "POST");
  405. }
  406. /// <summary>
  407. /// Performs a POST request
  408. /// </summary>
  409. /// <param name="options">The options.</param>
  410. /// <param name="postData">Params to add to the POST data.</param>
  411. /// <returns>stream on success, null on failure</returns>
  412. public async Task<Stream> Post(HttpRequestOptions options, Dictionary<string, string> postData)
  413. {
  414. options.SetPostData(postData);
  415. var response = await Post(options).ConfigureAwait(false);
  416. return response.Content;
  417. }
  418. /// <summary>
  419. /// Performs a POST request
  420. /// </summary>
  421. /// <param name="url">The URL.</param>
  422. /// <param name="postData">Params to add to the POST data.</param>
  423. /// <param name="resourcePool">The resource pool.</param>
  424. /// <param name="cancellationToken">The cancellation token.</param>
  425. /// <returns>stream on success, null on failure</returns>
  426. public Task<Stream> Post(string url, Dictionary<string, string> postData, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  427. {
  428. return Post(new HttpRequestOptions
  429. {
  430. Url = url,
  431. ResourcePool = resourcePool,
  432. CancellationToken = cancellationToken
  433. }, postData);
  434. }
  435. /// <summary>
  436. /// Downloads the contents of a given url into a temporary location
  437. /// </summary>
  438. /// <param name="options">The options.</param>
  439. /// <returns>Task{System.String}.</returns>
  440. /// <exception cref="System.ArgumentNullException">progress</exception>
  441. public async Task<string> GetTempFile(HttpRequestOptions options)
  442. {
  443. var response = await GetTempFileResponse(options).ConfigureAwait(false);
  444. return response.TempFilePath;
  445. }
  446. public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
  447. {
  448. ValidateParams(options);
  449. _fileSystem.CreateDirectory(_appPaths.TempDirectory);
  450. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  451. if (options.Progress == null)
  452. {
  453. throw new ArgumentNullException("progress");
  454. }
  455. options.CancellationToken.ThrowIfCancellationRequested();
  456. var httpWebRequest = GetRequest(options, "GET", options.EnableHttpCompression);
  457. if (options.ResourcePool != null)
  458. {
  459. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  460. }
  461. options.Progress.Report(0);
  462. if (options.LogRequest)
  463. {
  464. _logger.Info("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
  465. }
  466. var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
  467. try
  468. {
  469. options.CancellationToken.ThrowIfCancellationRequested();
  470. using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
  471. {
  472. var httpResponse = (HttpWebResponse)response;
  473. EnsureSuccessStatusCode(client, httpResponse, options);
  474. options.CancellationToken.ThrowIfCancellationRequested();
  475. var contentLength = GetContentLength(httpResponse);
  476. if (!contentLength.HasValue)
  477. {
  478. // We're not able to track progress
  479. using (var stream = httpResponse.GetResponseStream())
  480. {
  481. using (var fs = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  482. {
  483. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  484. }
  485. }
  486. }
  487. else
  488. {
  489. using (var stream = ProgressStream.CreateReadProgressStream(httpResponse.GetResponseStream(), options.Progress.Report, contentLength.Value))
  490. {
  491. using (var fs = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  492. {
  493. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  494. }
  495. }
  496. }
  497. options.Progress.Report(100);
  498. return GetResponseInfo(httpResponse, tempFile, contentLength);
  499. }
  500. }
  501. catch (Exception ex)
  502. {
  503. DeleteTempFile(tempFile);
  504. throw GetException(ex, options, client);
  505. }
  506. finally
  507. {
  508. if (options.ResourcePool != null)
  509. {
  510. options.ResourcePool.Release();
  511. }
  512. }
  513. }
  514. private long? GetContentLength(HttpWebResponse response)
  515. {
  516. var length = response.ContentLength;
  517. if (length == 0)
  518. {
  519. return null;
  520. }
  521. return length;
  522. }
  523. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  524. private Exception GetException(Exception ex, HttpRequestOptions options, HttpClientInfo client)
  525. {
  526. if (ex is HttpException)
  527. {
  528. return ex;
  529. }
  530. var webException = ex as WebException
  531. ?? ex.InnerException as WebException;
  532. if (webException != null)
  533. {
  534. if (options.LogErrors)
  535. {
  536. _logger.ErrorException("Error getting response from " + options.Url, ex);
  537. }
  538. var exception = new HttpException(ex.Message, ex);
  539. var response = webException.Response as HttpWebResponse;
  540. if (response != null)
  541. {
  542. exception.StatusCode = response.StatusCode;
  543. if ((int)response.StatusCode == 429)
  544. {
  545. client.LastTimeout = DateTime.UtcNow;
  546. }
  547. }
  548. return exception;
  549. }
  550. var operationCanceledException = ex as OperationCanceledException
  551. ?? ex.InnerException as OperationCanceledException;
  552. if (operationCanceledException != null)
  553. {
  554. return GetCancellationException(options, client, options.CancellationToken, operationCanceledException);
  555. }
  556. if (options.LogErrors)
  557. {
  558. _logger.ErrorException("Error getting response from " + options.Url, ex);
  559. }
  560. return ex;
  561. }
  562. private void DeleteTempFile(string file)
  563. {
  564. try
  565. {
  566. _fileSystem.DeleteFile(file);
  567. }
  568. catch (IOException)
  569. {
  570. // Might not have been created at all. No need to worry.
  571. }
  572. }
  573. private void ValidateParams(HttpRequestOptions options)
  574. {
  575. if (string.IsNullOrEmpty(options.Url))
  576. {
  577. throw new ArgumentNullException("options");
  578. }
  579. }
  580. /// <summary>
  581. /// Gets the host from URL.
  582. /// </summary>
  583. /// <param name="url">The URL.</param>
  584. /// <returns>System.String.</returns>
  585. private string GetHostFromUrl(string url)
  586. {
  587. var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase);
  588. if (index != -1)
  589. {
  590. url = url.Substring(index + 3);
  591. var host = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
  592. if (!string.IsNullOrWhiteSpace(host))
  593. {
  594. return host;
  595. }
  596. }
  597. return url;
  598. }
  599. /// <summary>
  600. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  601. /// </summary>
  602. public void Dispose()
  603. {
  604. Dispose(true);
  605. GC.SuppressFinalize(this);
  606. }
  607. /// <summary>
  608. /// Releases unmanaged and - optionally - managed resources.
  609. /// </summary>
  610. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  611. protected virtual void Dispose(bool dispose)
  612. {
  613. if (dispose)
  614. {
  615. _httpClients.Clear();
  616. }
  617. }
  618. /// <summary>
  619. /// Throws the cancellation exception.
  620. /// </summary>
  621. /// <param name="options">The options.</param>
  622. /// <param name="client">The client.</param>
  623. /// <param name="cancellationToken">The cancellation token.</param>
  624. /// <param name="exception">The exception.</param>
  625. /// <returns>Exception.</returns>
  626. private Exception GetCancellationException(HttpRequestOptions options, HttpClientInfo client, CancellationToken cancellationToken, OperationCanceledException exception)
  627. {
  628. // If the HttpClient's timeout is reached, it will cancel the Task internally
  629. if (!cancellationToken.IsCancellationRequested)
  630. {
  631. var msg = string.Format("Connection to {0} timed out", options.Url);
  632. if (options.LogErrors)
  633. {
  634. _logger.Error(msg);
  635. }
  636. client.LastTimeout = DateTime.UtcNow;
  637. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  638. return new HttpException(msg, exception)
  639. {
  640. IsTimedOut = true
  641. };
  642. }
  643. return exception;
  644. }
  645. private void EnsureSuccessStatusCode(HttpClientInfo client, HttpWebResponse response, HttpRequestOptions options)
  646. {
  647. var statusCode = response.StatusCode;
  648. var isSuccessful = statusCode >= HttpStatusCode.OK && statusCode <= (HttpStatusCode)299;
  649. if (!isSuccessful)
  650. {
  651. if (options.LogErrorResponseBody)
  652. {
  653. try
  654. {
  655. using (var stream = response.GetResponseStream())
  656. {
  657. if (stream != null)
  658. {
  659. using (var reader = new StreamReader(stream))
  660. {
  661. var msg = reader.ReadToEnd();
  662. _logger.Error(msg);
  663. }
  664. }
  665. }
  666. }
  667. catch
  668. {
  669. }
  670. }
  671. throw new HttpException(response.StatusDescription)
  672. {
  673. StatusCode = response.StatusCode
  674. };
  675. }
  676. }
  677. /// <summary>
  678. /// Posts the specified URL.
  679. /// </summary>
  680. /// <param name="url">The URL.</param>
  681. /// <param name="postData">The post data.</param>
  682. /// <param name="cancellationToken">The cancellation token.</param>
  683. /// <returns>Task{Stream}.</returns>
  684. public Task<Stream> Post(string url, Dictionary<string, string> postData, CancellationToken cancellationToken)
  685. {
  686. return Post(url, postData, null, cancellationToken);
  687. }
  688. private Task<WebResponse> GetResponseAsync(WebRequest request, TimeSpan timeout)
  689. {
  690. var taskCompletion = new TaskCompletionSource<WebResponse>();
  691. Task<WebResponse> asyncTask = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
  692. ThreadPool.RegisterWaitForSingleObject((asyncTask as IAsyncResult).AsyncWaitHandle, TimeoutCallback, request, timeout, true);
  693. var callback = new TaskCallback { taskCompletion = taskCompletion };
  694. asyncTask.ContinueWith(callback.OnSuccess, TaskContinuationOptions.NotOnFaulted);
  695. // Handle errors
  696. asyncTask.ContinueWith(callback.OnError, TaskContinuationOptions.OnlyOnFaulted);
  697. return taskCompletion.Task;
  698. }
  699. private static void TimeoutCallback(object state, bool timedOut)
  700. {
  701. if (timedOut)
  702. {
  703. WebRequest request = (WebRequest)state;
  704. if (state != null)
  705. {
  706. request.Abort();
  707. }
  708. }
  709. }
  710. private class TaskCallback
  711. {
  712. public TaskCompletionSource<WebResponse> taskCompletion;
  713. public void OnSuccess(Task<WebResponse> task)
  714. {
  715. taskCompletion.TrySetResult(task.Result);
  716. }
  717. public void OnError(Task<WebResponse> task)
  718. {
  719. if (task.Exception != null)
  720. {
  721. taskCompletion.TrySetException(task.Exception);
  722. }
  723. else
  724. {
  725. taskCompletion.TrySetException(new List<Exception>());
  726. }
  727. }
  728. }
  729. }
  730. }