private AmazonProduct GetContent(String ASin) { var content = ""; var client = new WebClient(); var headers = new WebHeaderCollection(); headers.Add(HttpRequestHeader.Accept, "text/html, application/xhtml+xml, */*"); //headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate"); headers.Add(HttpRequestHeader.AcceptLanguage, "en-GB"); headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"); client.Headers = headers; var rawhtml = client.DownloadString("http://www.amazon.co.uk/dp/"+ ASin); HtmlAgilityPack.HtmlDocument Html = new HtmlAgilityPack.HtmlDocument(); Html.LoadHtml(rawhtml); var title = GetTitle(Html); var description = GetDescription(Html); AmazonProduct prod = new AmazonProduct() { Description = description, Title = title }; return prod; }
public static WebHeaderCollection RetrieveApplicationWebHeaders(IOrganizationService organizationService) { WebHeaderCollection webHeaders = null; //Null validation if (organizationService != null) { //Retrieve application credentials that meet criteria QueryExpression query = new QueryExpression("essc_applicationcredential"); query.ColumnSet = new ColumnSet(new string[] { "essc_applicationkey" }); query.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0); //Active FilterExpression filterExpression = new FilterExpression(LogicalOperator.Or); filterExpression.AddCondition("essc_name", ConditionOperator.Equal, "CRM Application"); filterExpression.AddCondition("essc_name", ConditionOperator.Equal, "ADX Application"); filterExpression.AddCondition("essc_name", ConditionOperator.Equal, "ESSC Application"); query.Criteria.AddFilter(filterExpression); EntityCollection applicationCredentials = organizationService.RetrieveMultiple(query); //Null validation if (applicationCredentials != null && applicationCredentials.Entities.Any()) { Entity applicationCredential = applicationCredentials.Entities.FirstOrDefault(); webHeaders = new System.Net.WebHeaderCollection(); webHeaders.Add("X-HP-ESSC-ApplicationId", applicationCredential.Id.ToString()); webHeaders.Add("X-HP-ESSC-ApplicationKey", GetAttributeValue <string>("essc_applicationkey", applicationCredential)); } } return(webHeaders); }
private bool VerifyAddHeaderIsIllegal(WebHeaderCollection wrc, string header, string content, Type exceptionType) { bool res = true; try { Log.Comment("Set Headers Properties for header: '" + header + "', with value: '" + content + "'"); if (null == content) wrc.Add(header); else wrc.Add(header, content); Log.Comment("Illegal header was set: Failed."); res = false; } catch (Exception ex) { if (!HttpTests.ValidateException(ex, exceptionType)) { res = false; } } return res; }
public void IsWindowsAuthentication() { WebHeaderCollection headers = new WebHeaderCollection(); headers.Add(HttpResponseHeader.WwwAuthenticate, "Negotiate"); headers.Add(HttpResponseHeader.WwwAuthenticate, "NTLM"); HttpAuthenticationHeader authenticationHeader = new HttpAuthenticationHeader(headers); Assert.AreEqual("Negotiate,NTLM", authenticationHeader.AuthenticationType); }
public void DigestAuthenticationSchemeAdded() { WebHeaderCollection headers = new WebHeaderCollection(); headers.Add(HttpResponseHeader.WwwAuthenticate, "Digest realm='test'"); headers.Add(HttpResponseHeader.WwwAuthenticate, "NTLM"); HttpAuthenticationHeader authenticationHeader = new HttpAuthenticationHeader(headers); Assert.AreEqual("Digest,NTLM", authenticationHeader.AuthenticationType); }
protected static WebHeaderCollection GetHttpHeaders(BaseRequest request, Options options) { string randomString = DateTime.Now.ToString("ddMMyyyyhhmmssffff"); WebHeaderCollection headers = new WebHeaderCollection(); headers.Add("Accept", "application/json"); headers.Add(RANDOM_HEADER_NAME, randomString); headers.Add(CLIENT_VERSION, "iyzipay-dotnet-2.1.9"); headers.Add(AUTHORIZATION, PrepareAuthorizationString(request, randomString, options)); return headers; }
public void ManyAuthenticationSchemesAdded() { WebHeaderCollection headers = new WebHeaderCollection(); headers.Add(HttpResponseHeader.WwwAuthenticate, "Negotiate"); headers.Add(HttpResponseHeader.WwwAuthenticate, "NTLM"); headers.Add(HttpResponseHeader.WwwAuthenticate, "Basic realm='test'"); HttpAuthenticationHeader authenticationHeader = new HttpAuthenticationHeader(headers); Assert.AreEqual("Negotiate,NTLM,Basic", authenticationHeader.AuthenticationType); }
public RestRequest() { Headers = new WebHeaderCollection(); Headers.Add(HttpRequestHeader.CacheControl, "no-store, must-revalidate"); Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip"); Encoding = Encoding.UTF8; Resource = string.Empty; Timeout = 2000; Data = string.Empty; ContentType = ContentType.TextPlain; Method = HttpMethod.GET; }
private void PreparePackets(long length) { //string postData = "?" + string.Join("&", arguments.Select(x => x.Key + "=" + x.Value).ToArray()); postMethod = Encoding.Default.GetBytes(string.Format("POST {0} HTTP/1.1\r\n", url.AbsolutePath)); WebHeaderCollection headers = new WebHeaderCollection(); headers.Add(HttpRequestHeader.ContentType, "multipart/form-data; boundary=" + boundary); headers.Add(HttpRequestHeader.Host, url.DnsSafeHost); headers.Add(HttpRequestHeader.ContentLength, (request.Length + length + requestEnd.Length).ToString()); headers.Add(HttpRequestHeader.Connection, "Keep-Alive"); headers.Add(HttpRequestHeader.CacheControl, "no-cache"); headerBytes = headers.ToByteArray(); }
internal static HttpRequestInfo CreateHttpRequestInfo(string method, IDictionary<string, string> fields) { string query = MessagingUtilities.CreateQueryString(fields); UriBuilder requestUri = new UriBuilder("http://localhost/path"); WebHeaderCollection headers = new WebHeaderCollection(); MemoryStream ms = new MemoryStream(); if (method == "POST") { headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded"); StreamWriter sw = new StreamWriter(ms); sw.Write(query); sw.Flush(); ms.Position = 0; } else if (method == "GET") { requestUri.Query = query; } else { throw new ArgumentOutOfRangeException("method", method, "Expected POST or GET"); } HttpRequestInfo request = new HttpRequestInfo { HttpMethod = method, UrlBeforeRewriting = requestUri.Uri, Headers = headers, InputStream = ms, }; return request; }
public void SendBuildInfo(String buildInfoJson) { string url = _artifactoryUrl + BUILD_REST_URL; try { var bytes = Encoding.Default.GetBytes(buildInfoJson); { //Custom headers WebHeaderCollection headers = new WebHeaderCollection(); headers.Add(HttpRequestHeader.ContentType, "application/vnd.org.jfrog.build.BuildInfo+json"); _httpClient.getHttpClient().SetHeader(headers); HttpResponse response = _httpClient.getHttpClient().Execute(url, "PUT", bytes); //When sending build info, Expecting for NoContent (204) response from Artifactory if (response._statusCode != HttpStatusCode.NoContent) { throw new WebException("Failed to send build info:" + response._message); } } } catch (Exception we) { _log.Error(we.Message, we); throw new WebException("Exception in Uploading BuildInfo: " + we.Message, we); } }
public static TestableHttpWebResponse GetHttpWebResponse(HttpResponseSettings httpResponseSettings, Uri uri, string expectedContentType) { SerializationInfo si = new SerializationInfo(typeof(HttpWebResponse), new System.Runtime.Serialization.FormatterConverter()); StreamingContext sc = new StreamingContext(); WebHeaderCollection headers = new WebHeaderCollection(); foreach (var kvp in httpResponseSettings.HeaderValues) headers.Add(kvp.Key, kvp.Value); si.AddValue("m_HttpResponseHeaders", headers); si.AddValue("m_Uri", uri); si.AddValue("m_Certificate", null); si.AddValue("m_Version", HttpVersion.Version11); si.AddValue("m_StatusCode", httpResponseSettings.StatusCode); si.AddValue("m_ContentLength", 0); si.AddValue("m_Verb", "GET"); si.AddValue("m_StatusDescription", httpResponseSettings.StatusDescription); si.AddValue("m_MediaType", expectedContentType); var webResponse = new TestableHttpWebResponse(si, sc, httpResponseSettings.ResponseStream); if (httpResponseSettings.ExpectException) throw new WebException("This request failed", new Exception(httpResponseSettings.StatusDescription), WebExceptionStatus.ProtocolError, webResponse); else return webResponse; }
public void UpdateHttpHeader(WebHeaderCollection headers, Uri requestUri, string requestMethod) { if (headers != null && !string.IsNullOrEmpty(accessToken)) { headers.Add("Authorization", string.Format("Bearer {0}", accessToken)); } }
public static string ReadPageWithHeaders(string url, NameValueCollection headers, NameValueCollection outputHeaders) { WebRequest myWebRequest = WebRequest.Create(url); if (headers.Count > 0) { WebHeaderCollection webHeaders; webHeaders = new WebHeaderCollection(); foreach (string key in headers.Keys) { webHeaders.Add(key, headers[key]); } myWebRequest.Headers = webHeaders; } WebResponse myWebResponse = myWebRequest.GetResponse(); Stream ReceiveStream = myWebResponse.GetResponseStream(); Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); StreamReader readStream = new StreamReader(ReceiveStream, encode); string strResponse = readStream.ReadToEnd(); readStream.Close(); if (outputHeaders != null) { foreach (string key in myWebResponse.Headers.Keys) { outputHeaders.Add(key, myWebResponse.Headers[key]); } } myWebResponse.Close(); return strResponse; }
public string POSTNFC(string url, string query, string auth) { HttpWebRequest hwrq = CreateRequest(url); hwrq.CookieContainer = Cookies; hwrq.Method = "DELETE"; hwrq.ContentType = "application/x-www-form-urlencoded"; WebHeaderCollection webHeaderCollection = new System.Net.WebHeaderCollection(); Decryptor decryptor = new Decryptor("ckuJ1YQrX7ysO/WVHkowGA=="); hwrq.Credentials = new NetworkCredential("d.astahov", decryptor.DescryptStr, "GRADIENT"); WebProxy proxy = new System.Net.WebProxy("proxy-dc.gradient.ru", 3128); proxy.Credentials = hwrq.Credentials; hwrq.Proxy = proxy; webHeaderCollection.Add(System.Net.HttpRequestHeader.Authorization, string.Format("token {0}", auth)); hwrq.Headers.Add(webHeaderCollection); byte[] data = Encoding.UTF8.GetBytes(query); hwrq.ContentLength = data.Length; hwrq.GetRequestStream().Write(data, 0, data.Length); using (HttpWebResponse hwrs = (HttpWebResponse)hwrq.GetResponse()) { Cookies.Add(hwrs.Cookies); using (StreamReader sr = new StreamReader(hwrs.GetResponseStream(), Encoding.Default)) { return(hwrs.Headers.ToString() + sr.ReadToEnd().Trim()); } } }
internal void UpdateHttpHeader(WebHeaderCollection headers) { if (headers != null && !string.IsNullOrEmpty(accessToken)) { headers.Add("Authorization", string.Format("Bearer {0}", accessToken)); } }
public bool GetAccessToken(string code) { Dictionary<string, string> args = new Dictionary<string, string>(); args.Add("client_id", AuthInfo.Client_ID); args.Add("client_secret", AuthInfo.Client_Secret); args.Add("code", code); WebHeaderCollection headers = new WebHeaderCollection(); headers.Add("Accept", "application/json"); string response = SendPostRequest("https://github.com/login/oauth/access_token", args, headers: headers); if (!string.IsNullOrEmpty(response)) { OAuth2Token token = JsonConvert.DeserializeObject<OAuth2Token>(response); if (token != null && !string.IsNullOrEmpty(token.access_token)) { AuthInfo.Token = token; return true; } } return false; }
public static WebResponse Create(HttpStatusCode statusCode, IDictionary<string,string> headers, string body = null) { var type = typeof(HttpWebResponse); var assembly = Assembly.GetAssembly(type); var obj = assembly.CreateInstance("System.Net.HttpWebResponse"); var webHeaders = new WebHeaderCollection(); foreach (var header in headers) { webHeaders.Add(header.Key,header.Value); } Stream responseBodyStream = null; body = body ?? string.Empty; responseBodyStream = Utils.CreateStreamFromString(body); var statusFieldInfo = type.GetField("m_StatusCode", BindingFlags.NonPublic | BindingFlags.Instance); var headersFieldInfo = type.GetField("m_HttpResponseHeaders", BindingFlags.NonPublic | BindingFlags.Instance); var streamFieldInfo = type.GetField("m_ConnectStream", BindingFlags.NonPublic | BindingFlags.Instance); var contentLengthFieldInfo = type.GetField("m_ContentLength", BindingFlags.NonPublic | BindingFlags.Instance); statusFieldInfo.SetValue(obj, statusCode); headersFieldInfo.SetValue(obj, webHeaders); streamFieldInfo.SetValue(obj, responseBodyStream); contentLengthFieldInfo.SetValue(obj, responseBodyStream.Length); return obj as HttpWebResponse; }
public bool GetAccessToken(string code) { Dictionary<string, string> args = new Dictionary<string, string>(); args.Add("client_id", this.oAuthInfos.Client_ID); args.Add("client_secret", this.oAuthInfos.Client_Secret); args.Add("code", code); WebHeaderCollection headers = new WebHeaderCollection(); headers.Add("Accept", "application/json"); string response = this.SendPostRequest(this.GistCompleteUri.ToString(), args, headers: headers); if (!string.IsNullOrEmpty(response)) { OAuth2Token token = JsonConvert.DeserializeObject<OAuth2Token>(response); if (token != null && !string.IsNullOrEmpty(token.access_token)) { this.oAuthInfos.Token = token; return true; } } return false; }
public static void Test_WebHeader_01() { WebHeaderCollection headers = new WebHeaderCollection(); headers.Add("xxx", "yyy"); headers.Add("xxx", "yyy222"); headers.Add("zzz", "fff"); headers.Add("xxx", "ttt"); for (int i = 0; i < headers.Count; ++i) { string key = headers.GetKey(i); foreach (string value in headers.GetValues(i)) { Trace.WriteLine("{0}: {1}", key, value); } } }
/// <summary> /// See <see cref="HttpRequest.AppendHeaders"/>. /// </summary> protected override void AppendHeaders(WebHeaderCollection headers) { var oAuthHeader = OAuthHelper.ConstructOAuthHeader(SinaConstants.OAuthHeaderPrefix,Token); headers.Add(HttpRequestHeader.Authorization, oAuthHeader); base.AppendHeaders(headers); }
public void NonStandardAuthenticationHeaderAdded() { WebHeaderCollection headers = new WebHeaderCollection(); headers.Add(HttpResponseHeader.WwwAuthenticate, "Foo"); HttpAuthenticationHeader authenticationHeader = new HttpAuthenticationHeader(headers); Assert.AreEqual("Foo", authenticationHeader.AuthenticationType); }
public void IsBasicAuthentication() { WebHeaderCollection headers = new WebHeaderCollection(); headers.Add(HttpResponseHeader.WwwAuthenticate, "Basic realm='localhost'"); HttpAuthenticationHeader authenticationHeader = new HttpAuthenticationHeader(headers); Assert.AreEqual("Basic", authenticationHeader.AuthenticationType); }
private WebClient getWebClient() { WebClient wc = new WebClient(); WebHeaderCollection headers = new WebHeaderCollection(); headers.Add("User-Agent", BrowserUtil.ChromeUserAgent); wc.Headers = headers; return wc; }
internal Response(Uri uri, RootTree rootTree) { responseUri = uri; headerCollection = new WebHeaderCollection(); headerCollection.Add("Content-Type", "text/html; Charset=utf-16"); var data = Encoding.Unicode.GetBytes(rootTree.RenderUrl(uri.ToString(), out node)); responseStream = new MemoryStream(data, false); }
public Downloader(string sid, string queryid, CookieCollection cookies, WebHeaderCollection header = null) { QueryId = queryid; SID = sid; Cookies = cookies; if (header == null) { Header = new WebHeaderCollection(); Header.Add(HttpRequestHeader.CacheControl, "max-age=0"); Header.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch"); Header.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.8"); } else { Header = header; } }
static WebHeaderCollection Encode(IDictionary<string,string> headers) { var webHeaders = new WebHeaderCollection(); foreach (string header in headers.Keys) webHeaders.Add(HttpUtility.UrlEncode(header), HttpUtility.UrlEncode(headers[header])); return webHeaders; }
private static WebHeaderCollection GetCustomHeaders(Dictionary<string, string> headers) { WebHeaderCollection collection = new WebHeaderCollection(); foreach (var header in headers) { collection.Add(header.Key, header.Value); } return collection; }
public HttpResponseExpectation(HttpStatusCode expectedStatusCode, string expectedResult, NameValueCollection headers = null) { StatusCode = expectedStatusCode; ExpectedResult = expectedResult; Headers = new WebHeaderCollection(); if (headers != null) { Headers.Add(headers); } }
/// <summary> /// Determines whether the ASP.NET page returns valid HTML by checking the response against the W3C Markup Validator. /// </summary> /// <param name="testContext">The test context.</param> /// <returns> /// An object representing indicating whether the HTML generated is valid. /// </returns> public static W3CValidityCheckResult ReturnsValidHtml(TestContext testContext) { var result = new W3CValidityCheckResult(); WebHeaderCollection w3cResponseHeaders = new WebHeaderCollection(); using (var webClient = new WebClient()) { string html = GetPageHtml(webClient, testContext.RequestedPage.Request.Url); // Send to W3C validator string w3cUrl = "http://validator.w3.org/check"; webClient.Encoding = System.Text.Encoding.UTF8; var values = new NameValueCollection(); values.Add("fragment", html); values.Add("prefill", "0"); values.Add("group", "0"); values.Add("doctype", "inline"); try { _w3cValidatorBlock.WaitOne(); byte[] w3cRawResponse = webClient.UploadValues(w3cUrl, values); result.Body = Encoding.UTF8.GetString(w3cRawResponse); w3cResponseHeaders.Add(webClient.ResponseHeaders); String responsePath = Path.Combine(Directory.GetCurrentDirectory(), String.Format("{0}.html", testContext.TestName)); FileStream responseStream = new FileStream(responsePath, FileMode.CreateNew); responseStream.Write(w3cRawResponse, 0, w3cRawResponse.Length); responseStream.Close(); testContext.AddResultFile(responsePath); } finally { ThreadPool.QueueUserWorkItem(ResetBlocker); // Reset on background thread } } // Extract result from response headers int warnings = -1; int errors = -1; int.TryParse(w3cResponseHeaders["X-W3C-Validator-Warnings"], out warnings); int.TryParse(w3cResponseHeaders["X-W3C-Validator-Errors"], out errors); string status = w3cResponseHeaders["X-W3C-Validator-Status"]; result.WarningsCount = warnings; result.ErrorsCount = errors; result.IsValid = (!String.IsNullOrEmpty(status) && status.Equals("Valid", StringComparison.InvariantCultureIgnoreCase)); return result; }
public ShimWebResponse(Stream stream, Uri uri, string contentType, HttpStatusCode statusCode) : base() { _stream = stream; _uri = uri; _contentType = contentType; _headers = new WebHeaderCollection(); _statusCode = statusCode; _headers.Add("content-type", _contentType); }
static WebHeaderCollection Encode(IDictionary<string, string> headers) { var webHeaders = new WebHeaderCollection(); foreach (var pair in headers) { webHeaders.Add(HttpUtility.UrlEncode(pair.Key), HttpUtility.UrlEncode(pair.Value)); } return webHeaders; }
public string GetFileNFC(string url, string auth, string _fileName) { HttpWebRequest hwrq = CreateRequest(url); /*if (Environment.UserDomainName == "GRADIENT") * hwrq.Credentials = CredentialCache.DefaultNetworkCredentials; * else*/ { Decryptor decryptor = new Decryptor("ckuJ1YQrX7ysO/WVHkowGA=="); hwrq.Credentials = new NetworkCredential("d.astahov", decryptor.DescryptStr, "GRADIENT"); } WebProxy proxy = new System.Net.WebProxy("proxy-dc.gradient.ru", 3128); proxy.Credentials = hwrq.Credentials; hwrq.Proxy = proxy; WebHeaderCollection webHeaderCollection = new System.Net.WebHeaderCollection(); webHeaderCollection.Add(System.Net.HttpRequestHeader.Authorization, string.Format("token {0}", auth)); hwrq.Headers.Add(webHeaderCollection); hwrq.ContentType = "application/octet-stream"; HttpWebResponse hwrs; try { hwrs = (HttpWebResponse)hwrq.GetResponse(); Stream stream = hwrs.GetResponseStream(); Byte[] buffer = new System.Byte[16 * 1024]; int bytesRead = stream.Read(buffer, 0, buffer.Length); FileStream fileStream = System.IO.File.Create(_fileName); while (bytesRead > 0) { int int32 = bytesRead; fileStream.Write(buffer, 0, int32); bytesRead = stream.Read(buffer, 0, buffer.Length); } stream.Close(); stream.Dispose(); fileStream.Close(); fileStream.Dispose(); } catch (WebException e) { HttpWebResponse hwrsE = (HttpWebResponse)e.Response; using (StreamReader sr = new StreamReader(hwrsE.GetResponseStream(), Encoding.UTF8)) { return(sr.ReadToEnd().Trim()); } } return(""); }
//确认提交反结算 private void Btn_Enter_Click(object sender, EventArgs e) { HttpWebResponse response = null; if (this.TxtNote.Text != "") { Consumption cp = new Consumption(); List <Log> log = new List <Log>(); Log logs = new Log(); logs.note = this.TxtNote.Text; logs.operation = "RECHECKOUTING";//RECHECKOUTING log.Add(logs); cp.logs = log.ToArray(); cp.people = p_peopleCount; List <Payment> lps = new List <Payment>(); cp.payments = lps.ToArray(); try { System.Net.WebHeaderCollection headers = new System.Net.WebHeaderCollection(); headers.Add("Authorization", PassValue.token); response = Patch.PatchHttp(headers, "consumptions/" + p_ConsumptionsId, cp); PassValue.consumptionid = ""; Messagebox mb = new Messagebox(); PassValue.MessageInfor = "反结算成功!"; mb.ShowDialog(); this.Close(); } finally { if (response != null) { response.Close(); } } } else { Messagebox mb = new Messagebox(); PassValue.MessageInfor = "不能为空!"; mb.ShowDialog(); } }
private void PrintCashier() { ConsumptionObj obj = cqControl.GetlvConsumption().GetCurrentObj(); if (obj != null) { string Consumptionid = obj.Consumption.id; Task task = new Task(); task.kind = "invoice"; Consumption consumption = new Consumption(); consumption.id = Consumptionid; task.consumption = consumption; System.Net.WebHeaderCollection header = new System.Net.WebHeaderCollection(); header.Add("Authorization", PassValue.token); HttpWebResponse response = Post.PostHttp(header, "printing/tasks", task); if ((int)response.StatusCode >= 200 && (int)response.StatusCode < 300) { var jserConsumption = new JavaScriptSerializer(); consumption = jserConsumption.Deserialize<Consumption>(PassValue.statucode); } MessageBox.Show("打印成功!"); } }
WebHeaderCollection ReadHeaders(Stream stream, out byte [] retBuffer, out int status) { retBuffer = null; status = 200; byte [] buffer = new byte [1024]; MemoryStream ms = new MemoryStream(); bool gotStatus = false; WebHeaderCollection headers = null; while (true) { int n = stream.Read(buffer, 0, 1024); if (n == 0) { HandleError(WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders"); return(null); } ms.Write(buffer, 0, n); int start = 0; string str = null; headers = new WebHeaderCollection(); while (ReadLine(ms.GetBuffer(), ref start, (int)ms.Length, ref str)) { if (str == null) { int contentLen = 0; try { contentLen = int.Parse(headers["Content-Length"]); } catch { contentLen = 0; } if (ms.Length - start - contentLen > 0) { // we've read more data than the response header and conents, // give back extra data to the caller retBuffer = new byte[ms.Length - start - contentLen]; Buffer.BlockCopy(ms.GetBuffer(), start + contentLen, retBuffer, 0, retBuffer.Length); } else { // haven't read in some or all of the contents for the response, do so now FlushContents(stream, contentLen - (int)(ms.Length - start)); } return(headers); } if (gotStatus) { headers.Add(str); continue; } int spaceidx = str.IndexOf(' '); if (spaceidx == -1) { HandleError(WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2"); return(null); } status = (int)UInt32.Parse(str.Substring(spaceidx + 1, 3)); gotStatus = true; } } }
async Task <(WebHeaderCollection, byte[], int)> ReadHeaders(Stream stream, CancellationToken cancellationToken) { byte[] retBuffer = null; int status = 200; byte[] buffer = new byte[1024]; MemoryStream ms = new MemoryStream(); while (true) { cancellationToken.ThrowIfCancellationRequested(); int n = await stream.ReadAsync(buffer, 0, 1024, cancellationToken).ConfigureAwait(false); if (n == 0) { throw WebConnection.GetException(WebExceptionStatus.ServerProtocolViolation, null); } ms.Write(buffer, 0, n); int start = 0; string str = null; bool gotStatus = false; WebHeaderCollection headers = new WebHeaderCollection(); while (WebConnection.ReadLine(ms.GetBuffer(), ref start, (int)ms.Length, ref str)) { if (str == null) { int contentLen; var clengthHeader = headers["Content-Length"]; if (string.IsNullOrEmpty(clengthHeader) || !int.TryParse(clengthHeader, out contentLen)) { contentLen = 0; } if (ms.Length - start - contentLen > 0) { // we've read more data than the response header and conents, // give back extra data to the caller retBuffer = new byte[ms.Length - start - contentLen]; Buffer.BlockCopy(ms.GetBuffer(), start + contentLen, retBuffer, 0, retBuffer.Length); } else { // haven't read in some or all of the contents for the response, do so now FlushContents(stream, contentLen - (int)(ms.Length - start)); } return(headers, retBuffer, status); } if (gotStatus) { headers.Add(str); continue; } string[] parts = str.Split(' '); if (parts.Length < 2) { throw WebConnection.GetException(WebExceptionStatus.ServerProtocolViolation, null); } if (String.Compare(parts[0], "HTTP/1.1", true) == 0) { ProxyVersion = HttpVersion.Version11; } else if (String.Compare(parts[0], "HTTP/1.0", true) == 0) { ProxyVersion = HttpVersion.Version10; } else { throw WebConnection.GetException(WebExceptionStatus.ServerProtocolViolation, null); } status = (int)UInt32.Parse(parts[1]); if (parts.Length >= 3) { StatusDescription = String.Join(" ", parts, 2, parts.Length - 2); } gotStatus = true; } } }
State ReadTrailer(byte [] buffer, ref int offset, int size) { char c = '\0'; // short path if (trailerState == 2 && (char)buffer [offset] == '\r' && saved.Length == 0) { offset++; if (offset < size && (char)buffer [offset] == '\n') { offset++; return(State.None); } offset--; } int st = trailerState; string stString = "\r\n\r"; while (offset < size && st < 4) { c = (char)buffer [offset++]; if ((st == 0 || st == 2) && c == '\r') { st++; continue; } if ((st == 1 || st == 3) && c == '\n') { st++; continue; } if (st > 0) { saved.Append(stString.Substring(0, saved.Length == 0? st - 2: st)); st = 0; if (saved.Length > 4196) { ThrowProtocolViolation("Error reading trailer (too long)."); } } } if (st < 4) { trailerState = st; if (offset < size) { ThrowProtocolViolation("Error reading trailer."); } return(State.Trailer); } StringReader reader = new StringReader(saved.ToString()); string line; while ((line = reader.ReadLine()) != null && line != "") { headers.Add(line); } return(State.None); }
WebHeaderCollection ReadHeaders(Stream stream, out byte [] retBuffer, out int status) { retBuffer = null; status = 200; byte [] buffer = new byte [1024]; MemoryStream ms = new MemoryStream(); while (true) { int n = stream.Read(buffer, 0, 1024); if (n == 0) { HandleError(WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders"); return(null); } ms.Write(buffer, 0, n); int start = 0; string str = null; bool gotStatus = false; WebHeaderCollection headers = new WebHeaderCollection(); while (ReadLine(ms.GetBuffer(), ref start, (int)ms.Length, ref str)) { if (str == null) { int contentLen = 0; try { contentLen = int.Parse(headers["Content-Length"]); } catch { contentLen = 0; } if (ms.Length - start - contentLen > 0) { // we've read more data than the response header and conents, // give back extra data to the caller retBuffer = new byte[ms.Length - start - contentLen]; Buffer.BlockCopy(ms.GetBuffer(), start + contentLen, retBuffer, 0, retBuffer.Length); } else { // haven't read in some or all of the contents for the response, do so now FlushContents(stream, contentLen - (int)(ms.Length - start)); } return(headers); } if (gotStatus) { headers.Add(str); continue; } string[] parts = str.Split(' '); if (parts.Length < 2) { HandleError(WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2"); return(null); } if (String.Compare(parts [0], "HTTP/1.1", true) == 0) { Data.ProxyVersion = HttpVersion.Version11; } else if (String.Compare(parts [0], "HTTP/1.0", true) == 0) { Data.ProxyVersion = HttpVersion.Version10; } else { HandleError(WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2"); return(null); } status = (int)UInt32.Parse(parts [1]); if (parts.Length >= 3) { Data.StatusDescription = String.Join(" ", parts, 2, parts.Length - 2); } gotStatus = true; } } }