public void TestWebHeaderCollectionRemove() { WebHeaderCollection whc = new WebHeaderCollection(); whc.Add("some:stuff"); whc.Remove("some"); try { whc.Remove(null); Fail("Remove: failed to throw exception for null argument"); } catch (ArgumentNullException) { // Ok } try { whc.Remove("[NotValidHeader?]"); Fail("Remove: failed to throw exception for invalid header name: '[NotValidHeader?]'"); } catch (ArgumentException) { // Yep... } try { whc.Remove("accept"); Fail("Remove: failed to throw exception for restricted header 'accept'"); } catch (ArgumentException) { // Still moving along... } }
private byte[] ProcessResponseStream(HttpRequest request, Stream responseStream, WebHeaderCollection webHeaderCollection) { responseStream.Position = 0; if (responseStream.Length != 0) { var encoding = webHeaderCollection["Content-Encoding"]; if (encoding != null) { if (encoding.IndexOf("gzip") != -1) { responseStream = new GZipStream(responseStream, CompressionMode.Decompress); webHeaderCollection.Remove("Content-Encoding"); } else if (encoding.IndexOf("deflate") != -1) { responseStream = new DeflateStream(responseStream, CompressionMode.Decompress); webHeaderCollection.Remove("Content-Encoding"); } } } return(responseStream.ToBytes()); }
private byte[] ProcessResponseStream(HttpWebRequest webRequest, Stream responseStream, WebHeaderCollection webHeaderCollection) { responseStream.Position = 0; if (responseStream.Length != 0 && webRequest.AutomaticDecompression != DecompressionMethods.None) { var encoding = webHeaderCollection["Content-Encoding"]; if (encoding != null) { if (webRequest.AutomaticDecompression.HasFlag(DecompressionMethods.GZip) && encoding.IndexOf("gzip") != -1) { responseStream = new GZipStream(responseStream, CompressionMode.Decompress); webHeaderCollection.Remove("Content-Encoding"); } else if (webRequest.AutomaticDecompression.HasFlag(DecompressionMethods.Deflate) && encoding.IndexOf("deflate") != -1) { responseStream = new DeflateStream(responseStream, CompressionMode.Decompress); webHeaderCollection.Remove("Content-Encoding"); } } } return(responseStream.ToBytes()); }
public static void SetLinkingHeaders(this WebHeaderCollection headers, string requestId, string opId) { headers.Remove(OPERATION_HEADER); headers.Add(OPERATION_HEADER, opId); headers.Remove(REQUEST_HEADER); headers.Add(REQUEST_HEADER, requestId); }
/// <summary> /// Sets the authorization header that should be supplied on every request /// </summary> /// <param name="scheme">The scheme.</param> /// <param name="parameter">The parameter.</param> /// <exception cref="System.NotImplementedException"></exception> public void SetAuthorizationHeader(string scheme, string parameter) { if (string.IsNullOrEmpty(parameter)) { _defaultHeaders.Remove(HttpRequestHeader.Authorization); } else { _defaultHeaders[HttpRequestHeader.Authorization] = scheme + " " + parameter; } }
private void SetHeaderValue(HttpRequestHeader name, string value) { if (value != null) { _headers[name] = value; } else { _headers.Remove(name); } }
public void Remove_HeaderExists_RemovesFromCollection(string name) { var headers = new WebHeaderCollection() { { "name", "value" } }; headers.Remove(name); Assert.Empty(headers); headers.Remove(name); Assert.Empty(headers); }
private HttpWebRequest SetupWebClient() { HttpWebRequest _wc; try { var r = WebRequest.Create(new Uri(_URL)); _wc = r as HttpWebRequest; } catch (Exception) { #if DEBUG if (Debugger.IsAttached) { throw; } #endif return(null); } _wc.Timeout = _timeout; _wc.KeepAlive = false; _wc.Referer = _referrer; try { var accept = _headers.GetValues("Accept"); if (accept != null) { _wc.Accept = accept[0]; _headers.Remove("Accept"); } var host = _headers.GetValues("Host"); if (host != null) { _wc.Host = host[0]; _headers.Remove("Host"); } _wc.Headers = _headers; } catch (Exception ex) { if (System.Windows.Forms.MessageBox.Show("Error when setting headers:\r\n" + ex.Message + "\r\n\r\nContinue?", "Continue?", System.Windows.Forms.MessageBoxButtons.YesNo) != System.Windows.Forms.DialogResult.Yes) { Stop(); return(null); } } return(_wc); }
private void SetHeaderValue(HttpRequestHeader name, string value) { if (value != null) { _headers[name] = value; } else { #if PCL || NETFX_CORE || SILVERLIGHT throw new PlatformNotSupportedException("Header removal not supported on this platform"); #else _headers.Remove(name); #endif } }
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel) { HttpRequestMessageProperty httpRequest = null; if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name)) { httpRequest = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; } if (httpRequest == null) { httpRequest = new HttpRequestMessageProperty() { Method = "GET", SuppressEntityBody = true }; request.Properties.Add(HttpRequestMessageProperty.Name, httpRequest); } WebHeaderCollection headers = httpRequest.Headers; string token = cacheToken ? AppDomainHelper.TokenDictionary.GetToken(oAuth_Url, tenant_Id, client_Id, client_Secret, resource, grant_Type) : TokenDictionary.GetNewToken(oAuth_Url, tenant_Id, client_Id, client_Secret, resource, grant_Type).Token; //Remove the authorization header if already exists. headers.Remove(HttpRequestHeader.Authorization); headers.Add(HttpRequestHeader.Authorization, "Bearer " + token); return(null); }
/// <summary> /// Из входящего ответа от сайта делает исходящий ответ для пользователя. /// Копирует заголовки, а если есть, то и тело ответа. /// </summary> /// <param name="context"></param> /// <param name="incomingResponse"></param> public void SendResponse(HttpListenerContext context, HttpWebResponse incomingResponse) { WebHeaderCollection headers = incomingResponse.Headers; headers.Remove("Content-Length"); // Этот заголовок нельзя передавать в комплекте. context.Response.Headers = headers; if (incomingResponse.ContentLength > 0) { Stream receiveStream = incomingResponse.GetResponseStream(); MemoryStream ms = new MemoryStream(); try { receiveStream.CopyTo(ms); } catch (Exception e) { Console.WriteLine("e>{0:yyyy-MM-dd HH:mm:ss} SendResponse(): {1} {2}", DateTime.Now, e.Message, context.Response.RedirectLocation); } context.Response.ContentLength64 = ms.Length; // Восстанавливаем Content-Length if (ms.Length > 0) { ms.Position = 0; try { ms.CopyTo(context.Response.OutputStream); } catch (Exception e) { Console.WriteLine("e>{0:yyyy-MM-dd HH:mm:ss} SendResponse(): {1} {2}", DateTime.Now, e.Message, context.Response.RedirectLocation); } } } context.Response.OutputStream.Close(); }
public static void RemoveHeader(WebHeaderCollection headers) { if (!string.IsNullOrWhiteSpace(headers["FaultInjectionInfo"])) { headers.Remove("FaultInjectionInfo"); } }
public void InitializeRequest(Uri url, Method method, WebHeaderCollection head, int timeout) { if (url.Scheme.ToLower() == "https") { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors errors) => { return(true); //总是接受 }); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072; } Request = WebRequest.Create(url) as HttpWebRequest; Request.AllowAutoRedirect = true; Request.KeepAlive = false; Request.Method = method.ToString(); if (head.AllKeys.Contains("user-agent")) { Request.UserAgent = head.Get("user-agent"); head.Remove("user-agent"); } foreach (var item in head.AllKeys) { Request.Headers.Add(item, head.Get(item)); } Request.ContentType = "charset=UTF-8;"; Request.Timeout = timeout; }
public void Remove() { col.Remove("Name1"); col.Remove("NameNotExist"); Assert.AreEqual(1, col.Count, "#1"); /* * // this can only be tested in namespace System.Net * try { * WebHeaderCollection col2 = new WebHeaderCollection (true); * col2.Add ("Host", "foo"); * col2.Remove ("Host"); * Assert.Fail ("#2: should fail according to spec"); * } catch (ArgumentException) {} */ }
public void Custom_AddThenRemove_Success() { WebHeaderCollection w = new WebHeaderCollection(); w.Add("name", "value"); w.Remove("name"); Assert.Equal(0, w.Count); }
// Token: 0x0600052C RID: 1324 RVA: 0x0001CAE8 File Offset: 0x0001ACE8 protected override void AddProtocolSpecificHeadersToServerRequest(WebHeaderCollection headers) { base.AddProtocolSpecificHeadersToServerRequest(headers); if (this.proxyForSameOrgExchangeOAuthCallToLowerVersion) { headers.Remove("X-CommonAccessToken"); } }
private void SetSpecialHeaders(string headerName, string value) { _HttpRequestHeaders.Remove(headerName); if (value.Length != 0) { _HttpRequestHeaders.Add(headerName, value); } }
/// <summary> /// Prepara a requisição antes da solicitação /// </summary> /// <param name="request"></param> private void AddPostDataTo(HttpWebRequest request) { request.UserAgent = SettingsManager.GetSessionUserAgent(); WebHeaderCollection myWebHeaderCollection = request.Headers; myWebHeaderCollection.Add("Accept-Language", SettingsManager.GetSessionAcceptLanguage()); myWebHeaderCollection.Add("AcceptCharset", SettingsManager.GetSessionAcceptCharset()); myWebHeaderCollection.Add("TransferEncoding", SettingsManager.GetSessionTransferEncoding()); if (extraHeader != null) { foreach (var kv in extraHeader) { if (myWebHeaderCollection.Get(kv.Key) == null) { myWebHeaderCollection.Add(kv.Key, kv.Value); } } } if (toRemoveHeader != null) { foreach (var r in toRemoveHeader) { if (myWebHeaderCollection.Get(r) != null) { myWebHeaderCollection.Remove(r); } } } request.Referer = lasUrl; request.AllowAutoRedirect = this.AutoRedirect; //request.KeepAlive = true; if (IsXMLPost) { string payload = XmlToPost; byte[] buff = System.Text.Encoding.UTF8.GetBytes(payload); request.ContentLength = buff.Length; request.ContentType = "text/plain; charset=UTF-8"; System.IO.Stream reqStream = request.GetRequestStream(); reqStream.Write(buff, 0, buff.Length); } else { string payload = FormElements.AssemblePostPayload(); var enc = Encoding.GetEncoding("ISO-8859-1"); byte[] buff = enc.GetBytes(payload.ToCharArray()); request.ContentLength = buff.Length; request.ContentType = "application/x-www-form-urlencoded"; System.IO.Stream reqStream = request.GetRequestStream(); reqStream.Write(buff, 0, buff.Length); } }
public void Remove_EmptyCollection_Success() { WebHeaderCollection w = new WebHeaderCollection(); w.Remove("foo"); Assert.Equal(0, w.Count); Assert.Empty(w); Assert.Empty(w.AllKeys); }
/// <summary> /// Updates the header remove header if null. /// </summary> /// <param name="headerCollection">The header collection.</param> /// <param name="responseHeader">The response header.</param> /// <param name="headerValue">The header value.</param> private static void UpdateHeaderOrRemoveHeaderIfNull(WebHeaderCollection headerCollection, string responseHeader, string headerValue) { if (headerValue == null) { headerCollection.Remove(responseHeader); return; } headerCollection[responseHeader] = headerValue; }
public void RemoveRestricted() { col = CreateRestrictedHeaders(); try { col.Add("Host", "foo"); col.Remove("Host"); Assert.Fail("#2: should fail according to spec"); } catch (ArgumentException) {} }
public void Remove_SetThenRemove_Success(string setName, string removeName) { WebHeaderCollection w = new WebHeaderCollection(); w[setName] = "value"; w.Remove(removeName); Assert.Equal(0, w.Count); Assert.Empty(w); Assert.Empty(w.AllKeys); }
/// <summary> /// Perform a GET-like request /// </summary> /// <param name="host">URL</param> /// <param name="cc">Cookie container</param> /// <param name="headers">HTTP headers</param> /// <param name="method">HTTP method (GET by default)</param> /// <param name="AllowAutoRedirect">Allow 302 redirection handling in .NET FW or not</param> /// <returns>Server's response.</returns> public HttpResponse GET(string host, CookieContainer cc, WebHeaderCollection headers, string method = "GET", bool AllowAutoRedirect = false) { try { foreach (string badhost in ConfigFile.ForceHttps) { if (host.Substring(7).StartsWith(badhost)) { host = "https" + host.Substring(4); //Console.Write(" secure"); Console.WriteLine("Secure request."); } } HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(host); string UA = headers["User-Agent"] + " WebOne/" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); string Accept = headers["Accept"]; string Referer = headers["Referer"]; //undone: add other headers that cannot be passed directly to the webRequest.Headers foreach (string str in HeaderBanList) { headers.Remove(str); } webRequest.Headers = headers; webRequest.Accept = Accept ?? "*/*"; webRequest.UserAgent = UA ?? UA_Mozilla; if (Referer != null) { webRequest.Referer = Referer; } webRequest.Method = method; webRequest.AllowAutoRedirect = true; webRequest.CookieContainer = cc; webRequest.ProtocolVersion = HttpVersion.Version11; webRequest.KeepAlive = true; webRequest.AllowAutoRedirect = AllowAutoRedirect; webResponse = (HttpWebResponse)webRequest.GetResponse(); return(new HttpResponse(webResponse)); } catch (Exception) { throw; } /*finally * { * if (webResponse != null) * webResponse.Close(); * }*/ }
public void HttpRequestHeader_Add_Remove_Success() { WebHeaderCollection w = new WebHeaderCollection(); w.Add(HttpRequestHeader.Warning, "Warning1"); Assert.Equal(1, w.Count); Assert.Equal("Warning1", w[HttpRequestHeader.Warning]); Assert.Equal("Warning", w.AllKeys[0]); w.Remove(HttpRequestHeader.Warning); Assert.Equal(0, w.Count); }
/// <summary> /// Readd non-easy headers to request /// </summary> /// <param name="Headers">Raw request header collection</param> /// <param name="HWR">HttpWebRequest object</param> void AddHeaders(WebHeaderCollection Headers, HttpWebRequest HWR) { //see https://docs.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest.headers?view=netframework-4.6#remarks string UA = GetUserAgent(Headers["User-Agent"]); string Referer = Headers["Referer"]; string Accept = Headers["Accept"]; string ContentLength = Headers["Content-Length"]; string ContentType = Headers["Content-Type"]; string Expect = Headers["Expect"]; string Date = Headers["Date"]; string IfModifiedSince = Headers["If-Modified-Since"]; string Range = Headers["Range"]; foreach (string str in HeaderBanList) { Headers.Remove(str); } HWR.Headers = Headers; HWR.UserAgent = UA ?? UA_Mozilla; if (Referer != null) { HWR.Referer = Referer; } HWR.Accept = Accept ?? "*/*"; if (ContentLength != null) { HWR.ContentLength = long.Parse(ContentLength); } if (ContentType != null) { HWR.ContentType = ContentType; } if (Expect != null) { HWR.Expect = Expect; } if (Date != null) { HWR.Date = DateTime.Parse(Date); } DateTime IfModifiedSinceDT; if (IfModifiedSince != null && DateTime.TryParse(IfModifiedSince, out IfModifiedSinceDT)) { HWR.IfModifiedSince = IfModifiedSinceDT; } if (Range != null) { AddRangeHeader(Range, HWR); } }
public void HttpRequestHeader_Add_Rmemove_Success() { WebHeaderCollection w = new WebHeaderCollection(); w.Add(HttpRequestHeader.Warning, "Warning1"); Assert.Equal(1, w.Count); Assert.Equal("Warning1", w[HttpRequestHeader.Warning]); Assert.Equal("Warning", w.AllKeys[0]); w.Remove(HttpRequestHeader.Warning); Assert.Equal(0, w.Count); }
public void Remove_SetTwoThenRemoveOne_Success(string setName, string removeName) { WebHeaderCollection w = new WebHeaderCollection(); w[setName] = "value"; w["foo"] = "bar"; w.Remove(removeName); Assert.Equal(1, w.Count); Assert.NotEmpty(w); Assert.NotEmpty(w.AllKeys); Assert.Equal(new[] { "foo" }, w.AllKeys); Assert.Equal("bar", w["foo"]); }
/// <summary> /// See interface docs. /// </summary> /// <param name="key"></param> /// <returns></returns> public bool Remove(string key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } var countBeforeRemove = Count; _Collection.Remove(key); return(Count != countBeforeRemove); }
private void button2_Click(object sender, EventArgs e) { var item = listBox1.SelectedItem; if (item == null) { return; } _headers.Remove(item.ToString()); listBox1.Items.Remove(item); listBox2.Items.Clear(); }
public static WebHeaderCollection ToHeader(this WebHeaderCollection header, string stringifiedPayload, DateTime dt, bool addBearer = false) { header.Remove("X-Authorization"); header.Remove("X-Timestamp"); header.Remove("Authorization"); var keyByte = Encoding.UTF8.GetBytes(Constants.Key); var hmacsha1 = new HMACSHA1(keyByte); hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(stringifiedPayload)); header.Add("X-Timestamp", $"{dt:s}Z"); header.Add("X-Authorization", "HMAC " + ByteToString(hmacsha1.Hash)); if (addBearer) { header.Add("Authorization", "Bearer " + _user.AccessToken); } return(header); }
public static void Main() { // <Snippet1> try { // Create a web request for "www.msn.com". HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.msn.com"); // Get the headers associated with the request. WebHeaderCollection myWebHeaderCollection = myHttpWebRequest.Headers; // Set the Cache-Control header. myWebHeaderCollection.Set("Cache-Control", "no-cache"); // Get the associated response for the above request. HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); // Print the headers of the request to console. Console.WriteLine("Print request headers after adding Cache-Control for first request:"); printHeaders(myHttpWebRequest.Headers); // Remove the Cache-Control header for the new request. myWebHeaderCollection.Remove("Cache-Control"); // Get the response for the new request. myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); // Print the headers of the new request without the Cache-Control header. Console.WriteLine("Print request headers after removing Cache-Control for the new request:"); printHeaders(myHttpWebRequest.Headers); myHttpWebResponse.Close(); } // Catch exception if trying to remove a restricted header. catch (ArgumentException e) { Console.WriteLine("Error : Trying to remove a restricted header"); Console.WriteLine("ArgumentException is thrown. Message is :" + e.Message); } catch (WebException e) { Console.WriteLine("WebException is thrown. Message is :" + e.Message); if (e.Status == WebExceptionStatus.ProtocolError) { Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode); Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription); Console.WriteLine("Server : {0}", ((HttpWebResponse)e.Response).Server); } } catch (Exception e) { Console.WriteLine("Exception is thrown. Message is :" + e.Message); } // </Snippet1> }
public void HttpRequestHeader_Remove_Failure() { WebHeaderCollection w = new WebHeaderCollection(); Assert.Throws<ArgumentNullException>(() => w.Remove(null)); }
public void Custom_RemoveBlankName_Throws() { WebHeaderCollection w = new WebHeaderCollection(); Assert.Throws<ArgumentNullException>(() => w.Remove("")); }
public void Custom_RemoveIllegalCharacter_Throws() { WebHeaderCollection w = new WebHeaderCollection(); Assert.Throws<ArgumentException>(() => w.Remove("{")); }
public void Remove_IllegalCharacter_Throws() { WebHeaderCollection w = new WebHeaderCollection(); Assert.Throws<ArgumentException>("name", () => w.Remove("{")); }
public void Remove_NullOrEmptyName_Throws(string name) { WebHeaderCollection w = new WebHeaderCollection(); Assert.Throws<ArgumentNullException>("name", () => w.Remove(name)); }