private void SetSpecialHeaders(string HeaderName, string value) { _webHeaderCollection.Remove(HeaderName); if (!string.IsNullOrEmpty(value)) { _webHeaderCollection[HeaderName] = value; } }
internal HttpWebResponse(Uri uri, string method, WebResponseStream stream, CookieContainer container) { this.uri = uri; this.method = method; this.stream = stream; webHeaders = stream.Headers ?? new WebHeaderCollection(); version = stream.Version; statusCode = stream.StatusCode; statusDescription = stream.StatusDescription ?? HttpStatusDescription.Get(statusCode); contentLength = -1; try { string cl = webHeaders ["Content-Length"]; if (String.IsNullOrEmpty(cl) || !Int64.TryParse(cl, out contentLength)) { contentLength = -1; } } catch (Exception) { contentLength = -1; } if (container != null) { this.cookie_container = container; FillCookies(); } string content_encoding = webHeaders ["Content-Encoding"]; if (content_encoding == "gzip" && (stream.Request.AutomaticDecompression & DecompressionMethods.GZip) != 0) { this.stream = new GZipStream(stream, CompressionMode.Decompress); webHeaders.Remove(HttpRequestHeader.ContentEncoding); } else if (content_encoding == "deflate" && (stream.Request.AutomaticDecompression & DecompressionMethods.Deflate) != 0) { this.stream = new DeflateStream(stream, CompressionMode.Decompress); webHeaders.Remove(HttpRequestHeader.ContentEncoding); } }
public void RemoveRestricted () { col = CreateRestrictedHeaders (); try { col.Add ("Host", "foo"); col.Remove ("Host"); Assert.Fail ("#2: should fail according to spec"); } catch (ArgumentException) {} }
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(); }
public void Custom_AddThenRemove_Success() { WebHeaderCollection w = new WebHeaderCollection(); w.Add("name", "value"); w.Remove("name"); Assert.Equal(0, w.Count); }
public void Custom_RemoveIllegalCharacter_Throws() { WebHeaderCollection w = new WebHeaderCollection(); Assert.Throws<ArgumentException>(() => w.Remove("{")); }
public void Custom_RemoveBlankName_Throws() { WebHeaderCollection w = new WebHeaderCollection(); Assert.Throws<ArgumentNullException>(() => w.Remove("")); }
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 string[] provisionSend(string message, string method, string url, WebHeaderCollection headers) { url = Url + url; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); if (null != this.ProxyServer) request.Proxy = this.ProxyServer; request.Method = method; request.Timeout = Timeout * 1000; if (headers["Accept"] != null) { request.Accept = headers["Accept"]; headers.Remove("Accept"); } if (headers["Connection"] != null) { request.Connection = headers["Connection"]; headers.Remove("Connection"); } if (headers["Content-Length"] != null) { request.ContentLength = Convert.ToInt64(headers["Content-Length"]); headers.Remove("Content-Length"); } if (headers["Content-Type"] != null) { request.ContentType = headers["Content-Type"]; headers.Remove("Content-Type"); } if (headers["Expect"] != null) { request.Expect = headers["Expect"]; headers.Remove("Expect"); } if (headers["If-Modified-Since"] != null) { request.IfModifiedSince = Convert.ToDateTime(headers["If-Modified-Since"]); headers.Remove("If-Modified-Since"); } if (headers["Range"] != null) { request.AddRange(Convert.ToInt32(headers["Range"])); headers.Remove("Range"); } if (headers["Referer"] != null) { request.Referer = headers["Referer"]; headers.Remove("Referer"); } if (headers["Transfer-Encoding"] != null) { request.TransferEncoding = headers["Transfer-Encoding"]; headers.Remove("Transfer-Encoding"); } if (headers["User-Agent"] != null) { request.UserAgent = headers["User-Agent"]; headers.Remove("User-Agent"); } foreach (string key in headers.Keys) { if (request.Headers[key] != null) { request.Headers.Set(key, headers[key]); } else request.Headers.Add(key, headers[key]); } HttpWebResponse response = null; StreamReader reader = null; Stream stream = null; byte[] bytes = null; if (message != null) { bytes = Encoding.UTF8.GetBytes(message); request.ContentLength = bytes.Length; try { stream = request.GetRequestStream(); stream.Write(bytes, 0, bytes.Length); } catch (System.Exception e) { Console.WriteLine(e.Message); throw new HttpRPCRequestException("Unable to make http request."); } finally { if (stream != null) { stream.Close(); } } } try { response = (HttpWebResponse)request.GetResponse(); if (response == null) { return null; } reader = new StreamReader(response.GetResponseStream()); string recv = reader.ReadToEnd(); string statuscode; if (HttpStatusCode.OK == response.StatusCode || HttpStatusCode.ResetContent == response.StatusCode || HttpStatusCode.NoContent == response.StatusCode) { statuscode = response.StatusCode.ToString(); recv = statuscode + "\r\n" + recv; } else { statuscode = "FAIL"; recv = statuscode + "\r\n" + recv; } return new string[2] {statuscode, recv}; } catch (System.Exception e) { Console.WriteLine(e.Message); throw new HttpRPCResponseException("Unable to get http response."); } finally { if (response != null) { response.Close(); } if (reader != null) { reader.Close(); } } }
public MFTestResults TestWebHeaderCollectionRemove() { MFTestResults result = MFTestResults.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://" + Utilities.GetLocalIpAddress() + ":" + HttpServer.s_CurrentPort.ToString() + "/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.0"); wr.ProtocolVersion = new Version(1, 1); try { System.Net.WebHeaderCollection wrc = wr.Headers; int initialCount = wrc.Count; //set and remove individual header Log.Comment("Set and Remove HttpKnownHeaderNames.AcceptCharset"); wrc.Set(HttpKnownHeaderNames.AcceptCharset, "iso-8859-5, unicode-1-1;q=0.8"); wrc.Remove(HttpKnownHeaderNames.AcceptCharset); if (wrc.Count != initialCount) { result = MFTestResults.Fail; } Log.Comment("Set and Remove HttpKnownHeaderNames.AcceptEncoding"); wrc.Set(HttpKnownHeaderNames.AcceptEncoding, "compress;q=0.5, gzip;q=1.0"); wrc.Remove(HttpKnownHeaderNames.AcceptEncoding); if (wrc.Count != initialCount) { result = MFTestResults.Fail; } Log.Comment("Set and Remove HttpKnownHeaderNames.AcceptLanguage"); wrc.Set(HttpKnownHeaderNames.AcceptLanguage, "en-US"); wrc.Remove(HttpKnownHeaderNames.AcceptLanguage); if (wrc.Count != initialCount) { result = MFTestResults.Fail; } //Set and remove group of headers Log.Comment("Set group of headers..."); wrc.Set(HttpKnownHeaderNames.Age, "2 days"); wrc.Set(HttpKnownHeaderNames.Allow, "GET, PUT"); wrc.Set(HttpKnownHeaderNames.CacheControl, "no-cache"); wrc.Set(HttpKnownHeaderNames.ContentEncoding, "gzip"); wrc.Set(HttpKnownHeaderNames.ContentLanguage, "mi, en"); wrc.Set(HttpKnownHeaderNames.ContentMD5, "60e985979f1d55ab7542440fbb9659e5"); wrc.Set(HttpKnownHeaderNames.ContentRange, "bytes 21010-47021/47022"); wrc.Set(HttpKnownHeaderNames.Cookie, "www.google.com"); wrc.Set(HttpKnownHeaderNames.Expires, "Thu, 01 Dec 1994 16:00:00 GMT"); wrc.Set(HttpKnownHeaderNames.From, "*****@*****.**"); wrc.Set(HttpKnownHeaderNames.IfMatch, "r2d2xxxx"); wrc.Set(HttpKnownHeaderNames.IfNoneMatch, "xyzzy"); wrc.Set(HttpKnownHeaderNames.IfRange, "TestIfRange: Need to have Range Header."); wrc.Set(HttpKnownHeaderNames.IfUnmodifiedSince, "Fri, 22 May 2009 12:43:31 GMT"); wrc.Set(HttpKnownHeaderNames.KeepAlive, "true"); wrc.Set(HttpKnownHeaderNames.LastModified, "Fri, 22 May 2009 12:43:31 GMT"); wrc.Set(HttpKnownHeaderNames.MaxForwards, "10"); wrc.Set(HttpKnownHeaderNames.Pragma, "no-cache"); wrc.Set(HttpKnownHeaderNames.ProxyAuthenticate, ""); wrc.Set(HttpKnownHeaderNames.ProxyAuthorization, ""); wrc.Set(HttpKnownHeaderNames.RetryAfter, "100000"); wrc.Set(HttpKnownHeaderNames.Server, ""); wrc.Set(HttpKnownHeaderNames.SetCookie, "www.microsoft.com"); wrc.Set(HttpKnownHeaderNames.SetCookie2, "www.bing.com"); wrc.Set(HttpKnownHeaderNames.TE, "trailers, deflate;q=0.5"); wrc.Set(HttpKnownHeaderNames.Trailer, "Test Code"); wrc.Set(HttpKnownHeaderNames.Upgrade, "HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11"); wrc.Set(HttpKnownHeaderNames.Via, "1.0 fred, 1.1 nowhere.com (Apache/1.1)"); wrc.Set(HttpKnownHeaderNames.Vary, "*"); wrc.Set(HttpKnownHeaderNames.Warning, "TestWarning"); wrc.Set(HttpKnownHeaderNames.WWWAuthenticate, "WWW-Authenticate"); //remove headers Log.Comment("Remove group of headers..."); wrc.Remove(HttpKnownHeaderNames.Age); wrc.Remove(HttpKnownHeaderNames.Allow); wrc.Remove(HttpKnownHeaderNames.CacheControl); wrc.Remove(HttpKnownHeaderNames.ContentEncoding); wrc.Remove(HttpKnownHeaderNames.ContentLanguage); wrc.Remove(HttpKnownHeaderNames.ContentMD5); wrc.Remove(HttpKnownHeaderNames.ContentRange); wrc.Remove(HttpKnownHeaderNames.Cookie); wrc.Remove(HttpKnownHeaderNames.Expires); wrc.Remove(HttpKnownHeaderNames.From); wrc.Remove(HttpKnownHeaderNames.IfMatch); wrc.Remove(HttpKnownHeaderNames.IfNoneMatch); wrc.Remove(HttpKnownHeaderNames.IfRange); wrc.Remove(HttpKnownHeaderNames.IfUnmodifiedSince); wrc.Remove(HttpKnownHeaderNames.KeepAlive); wrc.Remove(HttpKnownHeaderNames.LastModified); wrc.Remove(HttpKnownHeaderNames.MaxForwards); wrc.Remove(HttpKnownHeaderNames.Pragma); wrc.Remove(HttpKnownHeaderNames.ProxyAuthenticate); wrc.Remove(HttpKnownHeaderNames.ProxyAuthorization); wrc.Remove(HttpKnownHeaderNames.RetryAfter); wrc.Remove(HttpKnownHeaderNames.Server); wrc.Remove(HttpKnownHeaderNames.SetCookie); wrc.Remove(HttpKnownHeaderNames.SetCookie2); wrc.Remove(HttpKnownHeaderNames.TE); wrc.Remove(HttpKnownHeaderNames.Trailer); wrc.Remove(HttpKnownHeaderNames.Upgrade); wrc.Remove(HttpKnownHeaderNames.Via); wrc.Remove(HttpKnownHeaderNames.Vary); wrc.Remove(HttpKnownHeaderNames.Warning); wrc.Remove(HttpKnownHeaderNames.WWWAuthenticate); if (wrc.Count != initialCount) { result = MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = MFTestResults.Fail; } return(result); }
public void MSOXCMAPIHTTP_S01_TC11_HTTPStatusCode() { this.CheckMapiHttpIsSupported(); WebHeaderCollection headers = new WebHeaderCollection(); CookieCollection cookies = new CookieCollection(); MailboxResponseBodyBase response; #region Send a Connect request type request which misses X-RequestId header. HttpStatusCode httpStatusCodeFailed; AdapterHelper.ClientInstance = Guid.NewGuid().ToString(); AdapterHelper.Counter = 1; headers = AdapterHelper.InitializeHTTPHeader(RequestType.Connect, AdapterHelper.ClientInstance, AdapterHelper.Counter); headers.Remove("X-RequestId"); this.Adapter.Connect(this.AdminUserName, this.AdminUserPassword, this.AdminUserDN, ref cookies, out response, ref headers, out httpStatusCodeFailed); // Add the debug information this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCMAPIHTTP_R143"); // Verify MS-OXCMAPIHTTP requirement: MS-OXCMAPIHTTP_R143 this.Site.CaptureRequirementIfAreEqual<uint>( 7, AdapterHelper.GetFinalResponseCode(headers["X-ResponseCode"]), 143, @"[In X-ResponseCode Header Field] Missing Header (7): The request has a missing required header."); // Add the debug information this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCMAPIHTTP_R49"); // Verify MS-OXCMAPIHTTP requirement: MS-OXCMAPIHTTP_R49 this.Site.CaptureRequirementIfAreEqual<HttpStatusCode>( HttpStatusCode.OK, httpStatusCodeFailed, 49, @"[In Common Response Format] The server returns a ""200 OK"" HTTP status code when the request failed for all non-exceptional failures."); #endregion #region Send a valid Connect request type to estabish a Session Context with the server. HttpStatusCode httpStatusCodeSucceed; AdapterHelper.ClientInstance = Guid.NewGuid().ToString(); AdapterHelper.Counter = 1; headers = AdapterHelper.InitializeHTTPHeader(RequestType.Connect, AdapterHelper.ClientInstance, AdapterHelper.Counter); string requestIdValue = headers["X-RequestId"]; cookies = new CookieCollection(); this.Adapter.Connect(this.AdminUserName, this.AdminUserPassword, this.AdminUserDN, ref cookies, out response, ref headers, out httpStatusCodeSucceed); Site.Assert.AreEqual<uint>(0, uint.Parse(headers["X-ResponseCode"]), "The server should return a Status 0 in X-ResponseCode header if client connect to server succeeded."); // Add the debug information this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCMAPIHTTP_R48"); // Verify MS-OXCMAPIHTTP requirement: MS-OXCMAPIHTTP_R48 this.Site.CaptureRequirementIfAreEqual<HttpStatusCode>( HttpStatusCode.OK, httpStatusCodeSucceed, 48, @"[In Common Response Format] The server returns a ""200 OK"" HTTP status code when the request succeeds."); // Add the debug information this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCMAPIHTTP_R2040"); // Verify MS-OXCMAPIHTTP requirement: MS-OXCMAPIHTTP_R2040 this.Site.CaptureRequirementIfAreEqual<string>( requestIdValue, headers["X-RequestId"], 2040, @"[In X-RequestId Header Field] the server MUST return this header [X-RequestId] with the same information in the response back to the client."); #endregion #region Send a Disconnect request type request to destroy the Session Context. this.Adapter.Disconnect(out response); #endregion #region Send an anonymous request that includes a Connect request type. System.Threading.Thread.Sleep(60000); HttpStatusCode httpStatusCodeUnauthorized; AdapterHelper.ClientInstance = Guid.NewGuid().ToString(); AdapterHelper.Counter = 1; headers = AdapterHelper.InitializeHTTPHeader(RequestType.Connect, AdapterHelper.ClientInstance, AdapterHelper.Counter); cookies = new CookieCollection(); this.Adapter.Connect(string.Empty, string.Empty, string.Empty, ref cookies, out response, ref headers, out httpStatusCodeUnauthorized); // Add the debug information this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCMAPIHTTP_R1331"); // Verify MS-OXCMAPIHTTP requirement: MS-OXCMAPIHTTP_R1331 this.Site.CaptureRequirementIfAreEqual<HttpStatusCode>( HttpStatusCode.Unauthorized, httpStatusCodeUnauthorized, 1331, @"[In Common Response Format] The server deviates from a ""200 OK"" HTTP status code for authentication (""401 Access Denied"")."); // Add the debug information this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCMAPIHTTP_R36"); // Verify MS-OXCMAPIHTTP requirement: MS-OXCMAPIHTTP_R36 this.Site.CaptureRequirementIfAreNotEqual<HttpStatusCode>( HttpStatusCode.OK, httpStatusCodeUnauthorized, 36, @"[In POST Method] No anonymous requests are allowed."); #endregion }
//////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Method to execute the request, and control the exceptions.</summary> /// <remarks> 2012/04/19. SSL Exception control code added. /// 2012/04/24. Null body controlled when PostWithout body.</remarks> /// <returns>The formated Generic Response. /// If Exception occurs (Http 400,500, timeout etc..), and properly formated exception will be thrown.</returns> //////////////////////////////////////////////////////////////////////////////////////////////////// private BV_Response Call() { BV_Response genericResponse = null; //CONFIGURING THE REQUEST CALL:--------- //Setting the Certificate if exists: if (certCollection != null) { request.ClientCertificates = certCollection; } //Setting the Timeout: request.Timeout = Constants.blueviaTimeout; //Allowing autoredirect: true by default //IN POST CASE(with body), the body and headders must be buildt: if (headers!=null) { WebHeaderCollection headerCollection = new WebHeaderCollection(); foreach (var pair in headers) { headerCollection.Add(pair.Key, pair.Value); } //Setting the Content-Type //first if the message is a multipart, setting the boundary in the header string contentType = null; headers.TryGetValue(HttpTools.ContetTypeKey, out contentType); if (contentType.Contains("multipart")) { string bodyInString = Encoding.Default.GetString(body); string boundary = bodyInString.Substring(2, bodyInString.IndexOf("\r\n") - 2); contentType = string.Format(contentType, boundary); } //The content-type header must be setted with the following instruction ... request.ContentType = contentType; //... so deleting from the headerCollection, to avoid an exception ... headerCollection.Remove(HttpTools.ContetTypeKey); //... when the whole collection of headers is setted. request.Headers.Add(headerCollection); if (body != null) { request.ContentLength = body.Length; //SENDING THE REQUEST FOR PETITIONS WITH BODY:--------- try { using (System.IO.Stream putStream = request.GetRequestStream()) { putStream.Write(body, 0, body.Length); } } catch (WebException e) { throw new BlueviaException( "SSL error: Unable to create secure channel: " + e.Message , ExceptionCode.ConnectionErrorException); } } } //SENDING THE REQUEST FOR PETITIONS WITHOUT BODY:--------- try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException e)//Only Bluevia Http Errors will be catched { response = (HttpWebResponse)e.Response; } //THE RESPONSE HAS BEEN RECEIVED:--------- //Checking the response status: if(response == null) { throw new BlueviaException( "Http error: Unable to create secure channel." , ExceptionCode.ConnectionErrorException); } if ((int)response.StatusCode >= 400) //HTTP Error { BV_ConnectorException ex = new BV_ConnectorException( response.StatusDescription , Convert.ToString((int)response.StatusCode)); ex.SetConnectorExceptionAdditionalData(CreateAdditionalData()); throw ex; } else //Correct Response { genericResponse = new BV_Response(); genericResponse.SetResponseStatus(Convert.ToString((int)response.StatusCode)); genericResponse.SetResponseData(response.StatusDescription); genericResponse.SetResponseAdditionalData(CreateAdditionalData()); } return genericResponse; }
/// <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; }