示例#1
0
        internal HttpResponse(HttpResponseMessage resp, byte[] body)
        {
            StatusCode          = resp.StatusCode;
            ReasonPhrase        = resp.ReasonPhrase;
            Headers             = resp.Headers;
            RequestMessage      = resp.RequestMessage;
            IsSuccessStatusCode = resp.IsSuccessStatusCode;
            RateLimit           = RateLimitInfo.FromHttp(resp);

            _body = body;
        }
示例#2
0
        internal async Task <HttpResponse> GetAsync(string url, CancellationToken token, IProgress <double> progress = null)
        {
            HttpResponseMessage resp = await Client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false);

            if ((int)resp.StatusCode == 429)
            {
                var ex = new RateLimitExceededException(resp);
                if (Options.HandleRateLimits == false)
                {
                    throw ex;
                }

                RateLimitInfo info = ex.RateLimit;
                TimeSpan      diff = info.Reset - DateTime.Now;

                int millis = (int)diff.TotalMilliseconds;
                if (millis > 0)
                {
                    await Task.Delay(millis).ConfigureAwait(false);
                }

                return(await GetAsync(url, token, progress).ConfigureAwait(false));
            }

            if (token.IsCancellationRequested)
            {
                throw new TaskCanceledException();
            }

            using MemoryStream ms = new MemoryStream();
            using Stream s        = await resp.Content.ReadAsStreamAsync().ConfigureAwait(false);

            byte[] buffer = new byte[1 << 13];
            int    bytesRead;

            long?contentLength = resp.Content.Headers.ContentLength;
            long totalRead     = 0;

            progress?.Report(0);

            while ((bytesRead = await s.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0)
            {
                if (token.IsCancellationRequested)
                {
                    throw new TaskCanceledException();
                }

                if (contentLength != null)
                {
                    double prog = (double)totalRead / (double)contentLength;
                    progress?.Report(prog);
                }

                await ms.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);

                totalRead += bytesRead;
            }

            progress?.Report(1);
            byte[] bytes = ms.ToArray();

            return(new HttpResponse(resp, bytes));
        }