HttpClientManager.cs 32 KB

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