/// <summary> /// Create the client /// </summary> /// <param name="client">The REST client that wants to create the HTTP client</param> /// <param name="request">The REST request for which the HTTP client is created</param> /// <returns>A new HttpClient object</returns> /// <remarks> /// The DefaultHttpClientFactory contains some helpful protected methods that helps gathering /// the data required for a proper configuration of the HttpClient. /// </remarks> public virtual IHttpClient CreateClient(IRestClient client, IRestRequest request) { var headers = new GenericHttpHeaders(); var httpClient = new DefaultHttpClient(this, headers) { BaseAddress = GetBaseAddress(client) }; if (client.Timeout.HasValue) { httpClient.Timeout = client.Timeout.Value; } var proxy = GetProxy(client); if (proxy != null) { httpClient.Proxy = new RequestProxyWrapper(proxy); } var cookieContainer = GetCookies(client, request); if (cookieContainer != null) { httpClient.CookieContainer = cookieContainer; } if (_setCredentials) { var credentials = client.Credentials; if (credentials != null) { httpClient.Credentials = credentials; } } return httpClient; }
public StringContent([NotNull] string value, [NotNull] Encoding encoding) { _value = value; _encoding = encoding; Headers = new GenericHttpHeaders(); Headers.TryAddWithoutValidation("Content-Type", $"text/plain; charset={encoding.WebName}"); }
/// <summary> /// Initializes a new instance of the <see cref="DefaultHttpResponseMessage"/> class. /// </summary> /// <param name="requestMessage">The request message for this response</param> /// <param name="responseMessage">The response message to wrap</param> /// <param name="exception">The exception that occurred during the request</param> public DefaultHttpResponseMessage([NotNull] IHttpRequestMessage requestMessage, [NotNull] HttpWebResponse responseMessage, [CanBeNull] WebException exception = null) { ResponseMessage = responseMessage; _exception = exception; _requestMessage = requestMessage; var responseHeaders = new GenericHttpHeaders(); var contentHeaders = new GenericHttpHeaders(); if (responseMessage.SupportsHeaders) { foreach (var headerName in responseMessage.Headers.AllKeys) { IHttpHeaders headers; if (headerName.StartsWith("Content-", StringComparison.OrdinalIgnoreCase)) { headers = contentHeaders; } else { headers = responseHeaders; } headers.TryAddWithoutValidation(headerName, responseMessage.Headers[headerName]); } } _content = new HttpWebResponseContent(contentHeaders, responseMessage); _responseHttpHeaders = responseHeaders; }
/// <summary> /// Create the request message /// </summary> /// <param name="client">The REST client that wants to create the HTTP request message</param> /// <param name="request">The REST request for which the HTTP request message is created</param> /// <param name="parameters">The request parameters for the REST request except the content header parameters (read-only)</param> /// <returns>A new HttpRequestMessage object</returns> /// <remarks> /// The DefaultHttpClientFactory contains some helpful protected methods that helps gathering /// the data required for a proper configuration of the HttpClient. /// </remarks> public virtual IHttpRequestMessage CreateRequestMessage(IRestClient client, IRestRequest request, IList<Parameter> parameters) { var address = GetMessageAddress(client, request); var method = GetHttpMethod(client, request); var headers = new GenericHttpHeaders(); AddHttpHeaderParameters(headers, request, parameters); return new DefaultHttpRequestMessage(method, address, headers, null); }
/// <summary> /// Asynchronously send a request /// </summary> /// <param name="request">The request do send</param> /// <param name="cancellationToken">The cancellation token used to signal an abortion</param> /// <returns>The task to query the response</returns> public async Task<IHttpResponseMessage> SendAsync(IHttpRequestMessage request, CancellationToken cancellationToken) { var uri = new Uri(BaseAddress, request.RequestUri); var wr = _httpClientFactory.CreateWebRequest(uri); if (wr.SupportsCookieContainer && CookieContainer != null) wr.CookieContainer = CookieContainer; if (Credentials != null) wr.Credentials = Credentials; wr.Method = request.Method.ToString(); #if !PCL wr.Proxy = Proxy ?? System.Net.WebRequest.DefaultWebProxy; #endif // Combine all headers into one header collection var headers = new GenericHttpHeaders(); if (request.Content?.Headers != null) { foreach (var header in request.Content.Headers.Where(x => !headers.Contains(x.Key))) { headers.TryAddWithoutValidation(header.Key, header.Value); } } if (request.Headers != null) { foreach (var header in request.Headers.Where(x => !headers.Contains(x.Key))) { headers.TryAddWithoutValidation(header.Key, header.Value); } } if (DefaultRequestHeaders != null) { foreach (var header in DefaultRequestHeaders.Where(x => !headers.Contains(x.Key))) { headers.TryAddWithoutValidation(header.Key, header.Value); } } bool hasContentLength = false; foreach (var header in headers) { var value = string.Join(",", header.Value); SetWebRequestHeaderValue(wr, header.Key, value); if (!hasContentLength && string.Equals(header.Key, "content-length", StringComparison.OrdinalIgnoreCase)) hasContentLength = true; } if (request.Content != null) { // Add content length if not provided by the user. if (!hasContentLength) { long contentLength; if (request.Content.TryComputeLength(out contentLength)) { #if PCL || NETFX_CORE || WINDOWS_STORE wr.Headers[HttpRequestHeader.ContentLength] = contentLength.ToString(); #else wr.ContentLength = contentLength; #endif } } try { #if PCL && ASYNC_PCL var getRequestStreamAsync = Task.Factory.FromAsync<Stream>(wr.BeginGetRequestStream, wr.EndGetRequestStream, null); var requestStream = await getRequestStreamAsync.HandleCancellation(cancellationToken); #else var requestStream = await wr.GetRequestStreamAsync().HandleCancellation(cancellationToken); #endif using (requestStream) { var temp = new MemoryStream(); await request.Content.CopyToAsync(temp); var buffer = temp.ToArray(); await requestStream.WriteAsync(buffer, 0, buffer.Length, cancellationToken); await requestStream.FlushAsync(cancellationToken); } } catch (OperationCanceledException) { wr.Abort(); throw; } } try { #if PCL && ASYNC_PCL var getResponseAsync = Task.Factory.FromAsync<WebResponse>(wr.BeginGetResponse, wr.EndGetResponse, null); var response = await getResponseAsync.HandleCancellation(cancellationToken); #else var response = await wr.GetResponseAsync().HandleCancellation(cancellationToken); #endif var httpWebResponse = response as HttpWebResponse; if (httpWebResponse == null) { response.Dispose(); throw new ProtocolViolationException("No HTTP request") { Data = { { "URI", wr.RequestUri }, }, }; } return new DefaultHttpResponseMessage(request, httpWebResponse); } catch (WebException ex) { var httpWebResponse = (HttpWebResponse)ex.Response; return new DefaultHttpResponseMessage(request, httpWebResponse, ex); } catch (OperationCanceledException) { wr.Abort(); throw; } }
/// <summary> /// Initializes a new instance of the <see cref="ByteArrayContent"/> class. /// </summary> /// <param name="data">The underlying binary data</param> public ByteArrayContent(byte[] data) { _data = data; Headers = new GenericHttpHeaders(); Headers.TryAddWithoutValidation("Content-Type", "application/octet-stream"); }