public async Task <HttpResponseMessage> SendAsync(HttpRequestMessage message, IHttpContent content, HttpRequestHeaderCollection headers = null, CancellationToken token = default(CancellationToken)) { return(await _client.SendRequestAsync(message, HttpCompletionOption.ResponseHeadersRead).AsTask(token)); }
public async Task <HttpResponseMessage> GetAsync(Uri uri, CancellationToken token = default(CancellationToken)) { HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, uri); HttpRequestHeaderCollection headers = DefaultHeaders; return(await SendAsync(message, headers, token)); }
public async Task <HttpResponseMessage> PostAsync(Uri uri, IHttpContent postContent, CancellationToken token = new CancellationToken()) { HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, uri) { Content = postContent }; HttpRequestHeaderCollection headers = DefaultHeaders; return(await SendAsync(message, postContent, headers, token)); }
public HttpAdapter() { userConfig = ((App)Application.Current).GetUserConfig(); ApiKey = userConfig.ApiKey; httpClient = null; httpHeader = null; uri = null; httpResponse = null; isSuccess = false; //httpContent = null; InitHttp(); }
// Get header values. public List <string> GetHeaderValues(HttpRequestHeaderCollection headers, string headerName) { var list = new List <string>(); var headerList = headers.ToList(); var values = headerList.Where(kvp => kvp.Key == headerName).Select(kvp => kvp.Value).Distinct().ToList(); foreach (var str in values) { list.Add(str.TrimStart(null)); } return(list); }
/// <summary> /// 将HttpItem的请求头信息设置到指定Http请求头 /// </summary> /// <param name="headers"></param> /// <param name="httpItem"></param> private void SetHeaders(HttpRequestHeaderCollection headers, HttpItem httpItem) { if (headers != null && httpItem != null) { if (!string.IsNullOrEmpty(httpItem.Accept)) { headers.Accept.TryParseAdd(httpItem.Accept); } if (!string.IsNullOrEmpty(httpItem.AcceptEncoding)) { headers.AcceptEncoding.TryParseAdd(httpItem.AcceptEncoding); } if (!string.IsNullOrEmpty(httpItem.AcceptLanguage)) { headers.AcceptLanguage.TryParseAdd(httpItem.AcceptLanguage); } //if (!string.IsNullOrEmpty(httpItem.ContentType)) //{ // headers.Add("Content-Type", httpItem.ContentType); //} if (!string.IsNullOrEmpty(httpItem.Host)) { headers.Host = new HostName(httpItem.Host); } if (!string.IsNullOrEmpty(httpItem.Referer)) { headers.Referer = new Uri(httpItem.Referer); } if (!string.IsNullOrEmpty(httpItem.UserAgent)) { headers.UserAgent.TryParseAdd(httpItem.UserAgent); } if (httpItem.Header?.Count > 0) { foreach (var item in httpItem.Header) { headers.Add(item.Key, item.Value); } } } }
private static void WriteHeaders(HttpRequestHeaderCollection headers) { if (headers == null) { return; } if (!headers.Any()) { return; } Write("Headers:"); foreach (var item in headers) { Write($"{item.Key}:{JsonConvert.SerializeObject(item.Value)}"); } }
public HttpStream(HttpRequestMessage req, int buffsize) { //初始化Size(获取全部内容长度) //var buff = WindowsRuntimeBuffer.Create(buffsize); using (HttpClient client = new HttpClient()) { var res = client.SendRequestAsync(req, HttpCompletionOption.ResponseHeadersRead).WaitResult(3000); var istream = res.Content.ReadAsInputStreamAsync().WaitResult(3000); Headers = req.Headers; Method = req.Method; RequestUri = req.RequestUri; Size = (long)res.Content.Headers.ContentLength.Value; Stream = istream.AsStreamForRead(); //规则 不能 边读边写 Stream.Position client.Dispose(); } }
/// <summary> /// Adds the User-Agent string to a request to identify it /// as coming from the WDPW Open Source project. /// </summary> /// <param name="client">The HTTP client on which to have the header set.</param> public void ApplyUserAgentHeader(HttpClient client) { string userAgentValue = UserAgentValue; #if WINDOWS_UWP Assembly asm = this.GetType().GetTypeInfo().Assembly; userAgentValue += "-v" + asm.GetName().Version.ToString(); userAgentValue += "-UWP"; HttpRequestHeaderCollection headers = client.DefaultRequestHeaders; #else Assembly asm = Assembly.GetExecutingAssembly(); userAgentValue += "-v" + asm.GetName().Version.ToString(); userAgentValue += "-dotnet"; HttpRequestHeaders headers = client.DefaultRequestHeaders; #endif // WINDOWS_UWP headers.Add(UserAgentName, userAgentValue); }
/// <summary> /// Applies the CSRF token to the HTTP client. /// </summary> /// <param name="client">The HTTP client on which to have the header set.</param> /// <param name="method">The HTTP method (ex: POST) that will be called on the client.</param> public void ApplyCSRFHeader( HttpClient client, HttpMethods method) { string headerName = "X-" + CsrfTokenName; string headerValue = this.csrfToken; if (string.Compare(method.ToString(), "get", true) == 0) { headerName = CsrfTokenName; headerValue = string.IsNullOrEmpty(this.csrfToken) ? "Fetch" : headerValue; } #if WINDOWS_UWP HttpRequestHeaderCollection headers = client.DefaultRequestHeaders; #else HttpRequestHeaders headers = client.DefaultRequestHeaders; #endif // WINDOWS_UWP headers.Add(headerName, headerValue); }
public void UpdateSoapActionHeader(HttpRequestHeaderCollection headers) { headers.Clear(); headers.Add("SOAPAction", SoapHeader); }
public NetworkService(Backend.INetworkClient networkClient, SettingsService settingsService) { _networkClient = networkClient; _settingsService = settingsService; _defaultHeaders = _networkClient.DefaultHeaders; }
// Get header values. public List<string> GetHeaderValues(HttpRequestHeaderCollection headers, string headerName) { var list = new List<string>(); var headerList = headers.ToList(); var values = headerList.Where(kvp => kvp.Key == headerName).Select(kvp => kvp.Value).Distinct().ToList(); foreach (var str in values) { list.Add(str.TrimStart(null)); } return list; }
/// <summary> /// 初始化函数 /// </summary> /// <param name="httpClient"></param> public void InitHttp() { httpClient = new Windows.Web.Http.HttpClient(); httpHeader = httpClient.DefaultRequestHeaders; }
internal HttpRequest() { Method = HttpMethods.GET; Headers = new HttpRequestHeaderCollection(); }
private static async Task<RTIHttpContent> CreateRequestContentAsync(HttpRequestMessage request, HttpRequestHeaderCollection rtHeaderCollection) { HttpContent content = request.Content; RTIHttpContent rtContent; ArraySegment<byte> buffer; // If we are buffered already, it is more efficient to send the data directly using the buffer with the // WinRT HttpBufferContent class than using HttpStreamContent. This also avoids issues caused by // a design limitation in the System.Runtime.WindowsRuntime System.IO.NetFxToWinRtStreamAdapter. if (content.TryGetBuffer(out buffer)) { rtContent = new RTHttpBufferContent(buffer.Array.AsBuffer(), (uint)buffer.Offset, (uint)buffer.Count); } else { Stream contentStream = await content.ReadAsStreamAsync().ConfigureAwait(false); if (contentStream is RTIInputStream) { rtContent = new RTHttpStreamContent((RTIInputStream)contentStream); } else if (contentStream is MemoryStream) { var memStream = contentStream as MemoryStream; if (memStream.TryGetBuffer(out buffer)) { rtContent = new RTHttpBufferContent(buffer.Array.AsBuffer(), (uint)buffer.Offset, (uint)buffer.Count); } else { byte[] byteArray = memStream.ToArray(); rtContent = new RTHttpBufferContent(byteArray.AsBuffer(), 0, (uint) byteArray.Length); } } else { rtContent = new RTHttpStreamContent(contentStream.AsInputStream()); } } // RTHttpBufferContent constructor automatically adds a Content-Length header. RTHttpStreamContent does not. // Clear any 'Content-Length' header added by the RTHttp*Content objects. We need to clear that now // and decide later whether we need 'Content-Length' or 'Transfer-Encoding: chunked' headers based on the // .NET HttpRequestMessage and Content header collections. rtContent.Headers.ContentLength = null; // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics. // Desktop System.Net allows both headers to be specified but ends up stripping out // 'Content-Length' and using chunked semantics. The WinRT APIs throw an exception so // we need to manually strip out the conflicting header to maintain app compatibility. if (request.Headers.TransferEncodingChunked.HasValue && request.Headers.TransferEncodingChunked.Value) { content.Headers.ContentLength = null; } else { // Trigger delayed header generation via TryComputeLength. This code is needed due to an outstanding // bug in HttpContentHeaders.ContentLength. See GitHub Issue #5523. content.Headers.ContentLength = content.Headers.ContentLength; } foreach (KeyValuePair<string, IEnumerable<string>> headerPair in content.Headers) { foreach (string value in headerPair.Value) { if (!rtContent.Headers.TryAppendWithoutValidation(headerPair.Key, value)) { // rtContent headers are restricted to a white-list of allowed headers, while System.Net.HttpClient's content headers // will allow custom headers. If something is not successfully added to the content headers, try adding them to the standard headers. bool success = rtHeaderCollection.TryAppendWithoutValidation(headerPair.Key, value); Debug.Assert(success); } } } return rtContent; }
private static async Task <RTIHttpContent> CreateRequestContentAsync(HttpRequestMessage request, HttpRequestHeaderCollection rtHeaderCollection) { HttpContent content = request.Content; RTIHttpContent rtContent; ArraySegment <byte> buffer; // If we are buffered already, it is more efficient to send the data directly using the buffer with the // WinRT HttpBufferContent class than using HttpStreamContent. This also avoids issues caused by // a design limitation in the System.Runtime.WindowsRuntime System.IO.NetFxToWinRtStreamAdapter. if (content.TryGetBuffer(out buffer)) { rtContent = new RTHttpBufferContent(buffer.Array.AsBuffer(), (uint)buffer.Offset, (uint)buffer.Count); } else { Stream contentStream = await content.ReadAsStreamAsync().ConfigureAwait(false); if (contentStream is RTIInputStream) { rtContent = new RTHttpStreamContent((RTIInputStream)contentStream); } else if (contentStream is MemoryStream) { var memStream = contentStream as MemoryStream; if (memStream.TryGetBuffer(out buffer)) { rtContent = new RTHttpBufferContent(buffer.Array.AsBuffer(), (uint)buffer.Offset, (uint)buffer.Count); } else { byte[] byteArray = memStream.ToArray(); rtContent = new RTHttpBufferContent(byteArray.AsBuffer(), 0, (uint)byteArray.Length); } } else { rtContent = new RTHttpStreamContent(contentStream.AsInputStream()); } } // RTHttpBufferContent constructor automatically adds a Content-Length header. RTHttpStreamContent does not. // Clear any 'Content-Length' header added by the RTHttp*Content objects. We need to clear that now // and decide later whether we need 'Content-Length' or 'Transfer-Encoding: chunked' headers based on the // .NET HttpRequestMessage and Content header collections. rtContent.Headers.ContentLength = null; // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics. // Desktop System.Net allows both headers to be specified but ends up stripping out // 'Content-Length' and using chunked semantics. The WinRT APIs throw an exception so // we need to manually strip out the conflicting header to maintain app compatibility. if (request.Headers.TransferEncodingChunked.HasValue && request.Headers.TransferEncodingChunked.Value) { content.Headers.ContentLength = null; } else { // Trigger delayed header generation via TryComputeLength. This code is needed due to an outstanding // bug in HttpContentHeaders.ContentLength. See GitHub Issue #5523. content.Headers.ContentLength = content.Headers.ContentLength; } foreach (KeyValuePair <string, IEnumerable <string> > headerPair in content.Headers) { foreach (string value in headerPair.Value) { if (!rtContent.Headers.TryAppendWithoutValidation(headerPair.Key, value)) { // rtContent headers are restricted to a white-list of allowed headers, while System.Net.HttpClient's content headers // will allow custom headers. If something is not successfully added to the content headers, try adding them to the standard headers. bool success = rtHeaderCollection.TryAppendWithoutValidation(headerPair.Key, value); Debug.Assert(success); } } } return(rtContent); }
public UwpHttpService() { this.httpClient = new HttpClient(GetProtocolFilter()); this.headers = httpClient.DefaultRequestHeaders; }