Ejemplo n.º 1
0
 public HttpEntity(HttpHeaderDictionary messageheaders, Stream entityBodyStream)
 {
     Headers = messageheaders;
     if (entityBodyStream != null)
     {
         Stream = new LengthTrackingStream(entityBodyStream);
     }
     Errors = new List <Error>();
 }
        public void the_correct_number_of_bytes_is_recorded()
        {
            var stream  = new MemoryStream();
            var tracker = new LengthTrackingStream(stream);

            stream.Write(new byte[2 << 4]);

            tracker.Length.ShouldBe(stream.Length);
            tracker.Length.ShouldBe(32);
        }
        public void the_correct_number_of_bytes_is_recorded()
        {
            var stream = new DeflateStream(new MemoryStream(), CompressionMode.Compress);

            var tracker = new LengthTrackingStream(stream);

            tracker.Write(new byte[50]);

            tracker.Length.ShouldBe(50);
        }
Ejemplo n.º 4
0
        private void internalPerform()
        {
            using (abortToken = new CancellationTokenSource())
                using (timeoutToken = new CancellationTokenSource())
                    using (var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(abortToken.Token, timeoutToken.Token))
                    {
                        try
                        {
                            PrePerform();

                            HttpRequestMessage request;

                            switch (Method)
                            {
                            default:
                                throw new InvalidOperationException($"HTTP method {Method} is currently not supported");

                            case HttpMethod.GET:
                                if (files.Count > 0)
                                {
                                    throw new InvalidOperationException($"Cannot use {nameof(AddFile)} in a GET request. Please set the {nameof(Method)} to POST.");
                                }

                                StringBuilder requestParameters = new StringBuilder();
                                foreach (var p in parameters)
                                {
                                    requestParameters.Append($@"{p.Key}={p.Value}&");
                                }
                                string requestString = requestParameters.ToString().TrimEnd('&');

                                request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, string.IsNullOrEmpty(requestString) ? Url : $"{Url}?{requestString}");
                                break;

                            case HttpMethod.POST:
                                request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, Url);

                                Stream postContent;

                                if (rawContent != null)
                                {
                                    if (parameters.Count > 0)
                                    {
                                        throw new InvalidOperationException($"Cannot use {nameof(AddRaw)} in conjunction with {nameof(AddParameter)}");
                                    }
                                    if (files.Count > 0)
                                    {
                                        throw new InvalidOperationException($"Cannot use {nameof(AddRaw)} in conjunction with {nameof(AddFile)}");
                                    }

                                    postContent         = new MemoryStream();
                                    rawContent.Position = 0;
                                    rawContent.CopyTo(postContent);
                                    postContent.Position = 0;
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(ContentType) && ContentType != form_content_type)
                                    {
                                        throw new InvalidOperationException($"Cannot use custom {nameof(ContentType)} in a POST request.");
                                    }

                                    ContentType = form_content_type;

                                    var formData = new MultipartFormDataContent(form_boundary);

                                    foreach (var p in parameters)
                                    {
                                        formData.Add(new StringContent(p.Value), p.Key);
                                    }

                                    foreach (var p in files)
                                    {
                                        var byteContent = new ByteArrayContent(p.Value);
                                        byteContent.Headers.Add("Content-Type", "application/octet-stream");
                                        formData.Add(byteContent, p.Key, p.Key);
                                    }

                                    postContent = formData.ReadAsStreamAsync().Result;
                                }

                                requestStream = new LengthTrackingStream(postContent);
                                requestStream.BytesRead.ValueChanged += v =>
                                {
                                    reportForwardProgress();
                                    UploadProgress?.Invoke(v, contentLength);
                                };

                                request.Content = new StreamContent(requestStream);
                                if (!string.IsNullOrEmpty(ContentType))
                                {
                                    request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(ContentType);
                                }
                                break;
                            }

                            if (!string.IsNullOrEmpty(Accept))
                            {
                                request.Headers.Accept.TryParseAdd(Accept);
                            }

                            foreach (var kvp in headers)
                            {
                                request.Headers.Add(kvp.Key, kvp.Value);
                            }

                            reportForwardProgress();
                            using (request)
                                response = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, linkedToken.Token).Result;

                            ResponseStream = CreateOutputStream();

                            switch (Method)
                            {
                            case HttpMethod.GET:
                                //GETs are easy
                                beginResponse(linkedToken.Token);
                                break;

                            case HttpMethod.POST:
                                reportForwardProgress();
                                UploadProgress?.Invoke(0, contentLength);

                                beginResponse(linkedToken.Token);
                                break;
                            }
                        }
                        catch (Exception) when(timeoutToken.IsCancellationRequested)
                        {
                            Complete(new WebException($"Request to {Url} timed out after {timeSinceLastAction / 1000} seconds idle (read {responseBytesRead} bytes).", WebExceptionStatus.Timeout));
                        }
                        catch (Exception) when(abortToken.IsCancellationRequested)
                        {
                            Complete(new WebException($"Request to {Url} aborted by user.", WebExceptionStatus.RequestCanceled));
                        }
                        catch (Exception e)
                        {
                            Complete(e);
                            throw;
                        }
                    }
        }