HttpClientManager.cs 32 KB

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