public ChunkStream (WebHeaderCollection headers) { this.headers = headers; saved = new StringBuilder (); chunks = new ArrayList (); chunkSize = -1; }
public void HttpRequestHeader_GetKey_Success() { WebHeaderCollection w = new WebHeaderCollection(); w.Add("header1", "value1"); w.Add("header1", "value2"); Assert.NotEmpty(w.GetKey(0)); }
internal HttpListenerRequest (HttpListenerContext context) { this.context = context; headers = new WebHeaderCollection (); input_stream = Stream.Null; version = HttpVersion.Version10; }
public ChunkStream(WebHeaderCollection headers) { _headers = headers; _chunkSize = -1; _chunks = new List<Chunk> (); _saved = new StringBuilder (); }
public static WebHeaderCollection HeaderInfo(String str) { WebHeaderCollection CC = new WebHeaderCollection(); HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(str); Req.Proxy = null; Req.UseDefaultCredentials = true; //YOU MUST ASSIGN A COOKIE CONTAINER FOR THE REQUEST TO PULL THE COOKIES //Req.Headers = CC; HttpWebResponse Res = (HttpWebResponse)Req.GetResponse(); //DUMP THE COOKIES Console.WriteLine("----- HEADERS -----"); if(Res.Headers != null && Res.Headers.Count != 0) { foreach (string key in Res.Headers) { Console.WriteLine("\t" + key.ToString() + "\t" + Res.Headers[key]); } } else { Console.WriteLine("No Headers"); } return Res.Headers; }
static void write(WebHeaderCollection headers) { for (int index = 0; index < headers.Count; index++) { Console.WriteLine("{0}: {1}", headers.Keys[index], headers[index]); } Console.WriteLine(""); }
public void HttpRequestHeader_ToByteArray_Success() { WebHeaderCollection w = new WebHeaderCollection(); w.Add("header1", "value1"); w.Add("header1", "value2"); byte[] byteArr = w.ToByteArray(); Assert.NotEmpty(byteArr); }
public void DefaultPropertyValues_ReturnEmptyAfterConstruction_Success() { WebHeaderCollection w = new WebHeaderCollection(); Assert.Equal(0, w.AllKeys.Length); Assert.Equal(0, w.Count); Assert.Equal("\r\n", w.ToString()); Assert.Empty(w); }
public void HttpRequest_AddQuery_CommonHeader_Success() { string headerValue = "value123"; WebHeaderCollection w = new WebHeaderCollection(); w[HttpRequestHeader.Accept] = headerValue; Assert.Equal(headerValue, w[HttpRequestHeader.Accept]); }
public void HttpRequestHeader_Get_Success() { WebHeaderCollection w = new WebHeaderCollection(); w.Add("header1", "value1"); w.Add("header1", "value2"); string[] values = w.GetValues(0); Assert.Equal("value1", values[0]); Assert.Equal("value2", values[1]); }
public void HttpRequestHeader_Add_Success() { WebHeaderCollection w = new WebHeaderCollection(); w[HttpRequestHeader.Connection] = "keep-alive"; Assert.Equal(1, w.Count); Assert.Equal("keep-alive", w[HttpRequestHeader.Connection]); Assert.Equal("Connection", w.AllKeys[0]); }
public void HttpResponseHeader_AddQuery_CommonHeader_Success() { string headerValue = "value123"; WebHeaderCollection w = new WebHeaderCollection(); w[HttpResponseHeader.ProxyAuthenticate] = headerValue; w[HttpResponseHeader.WwwAuthenticate] = headerValue; Assert.Equal(headerValue, w[HttpResponseHeader.ProxyAuthenticate]); Assert.Equal(headerValue, w[HttpResponseHeader.WwwAuthenticate]); }
public void CustomHeader_AddQuery_Success() { string customHeader = "Custom-Header"; string customValue = "Custom;.-Value"; WebHeaderCollection w = new WebHeaderCollection(); w[customHeader] = customValue; Assert.Equal(1, w.Count); Assert.Equal(customValue, w[customHeader]); Assert.Equal(customHeader, w.AllKeys[0]); }
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); }
public RTSPClient( string Host, int Port, string URL ) { host = Host; port = Port; url = URL; cseq = 0; UserAgent = "RTSPClient"; tcctrl = new TcpClient(); addheaders = new WebHeaderCollection(); }
public static IEnumerable<object[]> SerializeDeserialize_Roundtrip_MemberData() { for (int i = 0; i < 10; i++) { var wc = new WebHeaderCollection(); for (int j = 0; j < i; j++) { wc[$"header{j}"] = $"value{j}"; } yield return new object[] { wc }; } }
static WebHeaderCollection getHeader(System.Uri pUri) { var lHeader = new WebHeaderCollection(); //lHeader.Add("Host", pUri.Host); //lHeader.Add("Get", pUri.PathAndQuery); //lHeader.Add("Accept", "*/*"); lHeader.Add("Cache-Control", "no-cache"); //lHeader.Add("Connection", "Keep-Alive"); lHeader.Add("Pragma", "no-cache"); //lHeader.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"); return lHeader; }
public HttpWebRequestCore (HttpWebRequest parent, Uri uri) { if (uri == null) throw new ArgumentNullException ("uri"); this.uri = uri; if (parent == null) { // special case used for policy allow_read_buffering = true; method = "GET"; } else { allow_read_buffering = parent.AllowReadStreamBuffering; method = parent.Method; headers = parent.Headers; } }
public void TestWebHeaderCollectionAdd() { WebHeaderCollection whc = new WebHeaderCollection(); whc.Add("phony:header"); whc.Add("some", "stuff"); try { whc.Add("nonsenseheader"); Fail("Add: failed to throw exception for missing colon"); } catch (ArgumentException) { // So far, so good. } try { whc.Add(null); Fail("Add: failed to throw exception for null header"); } catch (ArgumentNullException) { // Still ok... } try { whc.Add(null, "theOtherCtor"); Fail("Add: failed to throw header for null name"); } catch (ArgumentNullException) { // Onward and upward... } try { whc.Add("accept:betterNot"); Fail("Add: failed to throw exception for restricted header"); } catch (ArgumentException) { // Add looks good... } }
public BrowserHttpWebResponse (HttpWebRequest request, IntPtr native) { this.request = request; this.response = new MemoryStream (); progressive = request.AllowReadStreamBuffering; Headers = new WebHeaderCollection (); SetMethod (request.Method); if (native == IntPtr.Zero) return; // Get the status code and status text asap, this way we don't have to // ref/unref the native ptr int status_code = NativeMethods.http_response_get_response_status (native); SetStatus ((HttpStatusCode) status_code, (status_code == 200 || status_code == 404) ? NativeMethods.http_response_get_response_status_text (native) : "Requested resource was not found"); GCHandle handle = GCHandle.Alloc (this); NativeMethods.http_response_visit_headers (native, OnHttpHeader, GCHandle.ToIntPtr (handle)); handle.Free (); }
/// <summary> /// Adds header information that authenticates the request to Tableau Online /// </summary> /// <param name="webHeaders"></param> private void AppendLoggedInHeadersForRequest(WebHeaderCollection webHeaders) { webHeaders.Add("X-Tableau-Auth", _onlineSession.LogInAuthToken); _onlineSession.StatusLog.AddStatus("Append header X-Tableau-Auth: " + _onlineSession.LogInAuthToken, -20); }
// Constructors internal FileWebRequest(Uri uri) { this.uri = uri; this.webHeaders = new WebHeaderCollection(); }
public void Remove_IllegalCharacter_Throws() { WebHeaderCollection w = new WebHeaderCollection(); AssertExtensions.Throws <ArgumentException>("name", () => w.Remove("{")); }
public void Add_InvalidHeader_ThrowsArgumentException(string header, string paramName) { var headers = new WebHeaderCollection(); AssertExtensions.Throws <ArgumentException>(paramName, () => headers.Add(header)); }
/// <summary> /// Invokes the specified method against the url provided /// </summary> /// <param name="method">Method.</param> /// <param name="url">URL.</param> /// <param name="contentType">Content type.</param> /// <param name="body">Body.</param> /// <param name="query">Query.</param> /// <typeparam name="TBody">The 1st type parameter.</typeparam> /// <typeparam name="TResult">The 2nd type parameter.</typeparam> protected override TResult InvokeInternal <TBody, TResult>(string method, string url, string contentType, WebHeaderCollection additionalHeaders, out WebHeaderCollection responseHeaders, TBody body, NameValueCollection query) { if (String.IsNullOrEmpty(method)) { throw new ArgumentNullException(nameof(method)); } //if (String.IsNullOrEmpty(url)) // throw new ArgumentNullException(nameof(url)); // Three times: // 1. With provided credential // 2. With challenge // 3. With challenge again for (int i = 0; i < 2; i++) { // Credentials provided ? HttpWebRequest requestObj = this.CreateHttpRequest(url, query) as HttpWebRequest; if (!String.IsNullOrEmpty(contentType)) { requestObj.ContentType = contentType; } requestObj.Method = method; // Additional headers if (additionalHeaders != null) { foreach (var hdr in additionalHeaders.AllKeys) { if (hdr == "If-Modified-Since") { requestObj.IfModifiedSince = DateTime.Parse(additionalHeaders[hdr]); } else { requestObj.Headers.Add(hdr, additionalHeaders[hdr]); } } } #if PERFMON Stopwatch sw = new Stopwatch(); sw.Start(); #endif // Body was provided? try { // Try assigned credentials IBodySerializer serializer = null; if (body != null) { // GET Stream, Stream requestStream = null; try { // Get request object using (var requestTask = Task.Run(async() => { return(await requestObj.GetRequestStreamAsync()); })) { try { if (!requestTask.Wait(this.Description.Endpoint[0].Timeout)) { requestObj.Abort(); throw new TimeoutException(); } requestStream = requestTask.Result; } catch (AggregateException e) { requestObj.Abort(); throw e.InnerExceptions.First(); } } if (contentType == null && typeof(TResult) != typeof(Object)) { throw new ArgumentNullException(nameof(contentType)); } serializer = this.Description.Binding.ContentTypeMapper.GetSerializer(contentType, typeof(TBody)); // Serialize and compress with deflate using (MemoryStream ms = new MemoryStream()) { if (this.Description.Binding.Optimize) { switch ((this.Description.Binding as ServiceClientBinding)?.OptimizationMethod) { case OptimizationMethod.Lzma: requestObj.Headers.Add("Content-Encoding", "lzma"); using (var df = new LZipStream(requestStream, CompressionMode.Compress, leaveOpen: true)) serializer.Serialize(df, body); break; case OptimizationMethod.Bzip2: requestObj.Headers.Add("Content-Encoding", "bzip2"); using (var df = new BZip2Stream(requestStream, CompressionMode.Compress, leaveOpen: true)) serializer.Serialize(df, body); break; case OptimizationMethod.Gzip: requestObj.Headers.Add("Content-Encoding", "gzip"); using (var df = new GZipStream(requestStream, CompressionMode.Compress, leaveOpen: true)) serializer.Serialize(df, body); break; case OptimizationMethod.Deflate: requestObj.Headers.Add("Content-Encoding", "deflate"); using (var df = new DeflateStream(requestStream, CompressionMode.Compress, leaveOpen: true)) serializer.Serialize(df, body); break; case OptimizationMethod.None: default: serializer.Serialize(ms, body); break; } } else { serializer.Serialize(ms, body); } // Trace if (this.Description.Trace) { this.m_tracer.TraceVerbose("HTTP >> {0}", Convert.ToBase64String(ms.ToArray())); } using (var nms = new MemoryStream(ms.ToArray())) nms.CopyTo(requestStream); } } finally { if (requestStream != null) { requestStream.Dispose(); } } } // Response HttpWebResponse response = null; try { // Get request object using (var responseTask = Task.Run(async() => { return(await requestObj.GetResponseAsync()); })) { try { if (!responseTask.Wait(this.Description.Endpoint[0].Timeout)) { requestObj.Abort(); throw new TimeoutException(); } response = (HttpWebResponse)responseTask.Result; } catch (AggregateException e) { requestObj.Abort(); throw e.InnerExceptions.First(); } } #if PERFMON sw.Stop(); ApplicationContext.Current.PerformanceLog(nameof(RestClient), "InvokeInternal", $"{nameof(TBody)}-RCV", sw.Elapsed); sw.Reset(); sw.Start(); #endif responseHeaders = response.Headers; var validationResult = this.ValidateResponse(response); if (validationResult != ServiceClientErrorType.Valid) { this.m_tracer.TraceError("Response failed validation : {0}", validationResult); throw new WebException(Strings.err_response_failed_validation, null, WebExceptionStatus.Success, response); } // No content - does the result want a pointer maybe? if (response.StatusCode == HttpStatusCode.NoContent) { return(default(TResult)); } else { // De-serialize var responseContentType = response.ContentType; if (String.IsNullOrEmpty(responseContentType)) { return(default(TResult)); } if (responseContentType.Contains(";")) { responseContentType = responseContentType.Substring(0, responseContentType.IndexOf(";")); } if (response.StatusCode == HttpStatusCode.NotModified) { return(default(TResult)); } serializer = this.Description.Binding.ContentTypeMapper.GetSerializer(responseContentType, typeof(TResult)); TResult retVal = default(TResult); // Compression? using (MemoryStream ms = new MemoryStream()) { if (this.Description.Trace) { this.m_tracer.TraceVerbose("Received response {0} : {1} bytes", response.ContentType, response.ContentLength); } response.GetResponseStream().CopyTo(ms); #if PERFMON sw.Stop(); ApplicationContext.Current.PerformanceLog(nameof(RestClient), "InvokeInternal", $"{nameof(TBody)}-INT", sw.Elapsed); sw.Reset(); sw.Start(); #endif ms.Seek(0, SeekOrigin.Begin); // Trace if (this.Description.Trace) { this.m_tracer.TraceVerbose("HTTP << {0}", Convert.ToBase64String(ms.ToArray())); } switch (response.Headers[HttpResponseHeader.ContentEncoding]) { case "deflate": using (DeflateStream df = new DeflateStream(ms, CompressionMode.Decompress, leaveOpen: true)) retVal = (TResult)serializer.DeSerialize(df); break; case "gzip": using (GZipStream df = new GZipStream(ms, CompressionMode.Decompress, leaveOpen: true)) retVal = (TResult)serializer.DeSerialize(df); break; case "bzip2": using (var bzs = new BZip2Stream(ms, CompressionMode.Decompress, leaveOpen: true)) retVal = (TResult)serializer.DeSerialize(bzs); break; case "lzma": using (var lzmas = new LZipStream(ms, CompressionMode.Decompress, leaveOpen: true)) retVal = (TResult)serializer.DeSerialize(lzmas); break; default: retVal = (TResult)serializer.DeSerialize(ms); break; } //retVal = (TResult)serializer.DeSerialize(ms); } #if PERFMON sw.Stop(); ApplicationContext.Current.PerformanceLog(nameof(RestClient), "InvokeInternal", $"{nameof(TBody)}-RET", sw.Elapsed); sw.Reset(); sw.Start(); #endif return(retVal); } } finally { if (response != null) { response.Close(); response.Dispose(); } //responseTask.Dispose(); } } catch (TimeoutException e) { this.m_tracer.TraceError("Request timed out:{0}", e.Message); throw; } catch (WebException e) { var errorResponse = (e.Response as HttpWebResponse); if (errorResponse?.StatusCode == HttpStatusCode.NotModified) { this.m_tracer.TraceInfo("Server indicates not modified {0} {1} : {2}", method, url, e.Message); responseHeaders = errorResponse?.Headers; return(default(TResult)); } this.m_tracer.TraceError("Error executing {0} {1} : {2}", method, url, e.Message); // status switch (e.Status) { case WebExceptionStatus.ProtocolError: // Deserialize object errorResult = default(ErrorResult); var responseContentType = errorResponse.ContentType; if (responseContentType.Contains(";")) { responseContentType = responseContentType.Substring(0, responseContentType.IndexOf(";")); } var ms = new MemoryStream(); // copy response to memory errorResponse.GetResponseStream().CopyTo(ms); ms.Seek(0, SeekOrigin.Begin); try { var serializer = this.Description.Binding.ContentTypeMapper.GetSerializer(responseContentType, typeof(TResult)); try { switch (errorResponse.Headers[HttpResponseHeader.ContentEncoding]) { case "deflate": using (DeflateStream df = new DeflateStream(ms, CompressionMode.Decompress, leaveOpen: true)) errorResult = (TResult)serializer.DeSerialize(df); break; case "gzip": using (GZipStream df = new GZipStream(ms, CompressionMode.Decompress, leaveOpen: true)) errorResult = (TResult)serializer.DeSerialize(df); break; case "bzip2": using (var bzs = new BZip2Stream(ms, CompressionMode.Decompress, leaveOpen: true)) errorResult = (TResult)serializer.DeSerialize(bzs); break; case "lzma": using (var lzmas = new LZipStream(ms, CompressionMode.Decompress, leaveOpen: true)) errorResult = (TResult)serializer.DeSerialize(lzmas); break; default: errorResult = (TResult)serializer.DeSerialize(ms); break; } } catch { serializer = this.Description.Binding.ContentTypeMapper.GetSerializer(responseContentType, typeof(ErrorResult)); ms.Seek(0, SeekOrigin.Begin); // rewind and try generic error codes switch (errorResponse.Headers[HttpResponseHeader.ContentEncoding]) { case "deflate": using (DeflateStream df = new DeflateStream(ms, CompressionMode.Decompress, leaveOpen: true)) errorResult = (ErrorResult)serializer.DeSerialize(df); break; case "gzip": using (GZipStream df = new GZipStream(ms, CompressionMode.Decompress, leaveOpen: true)) errorResult = (ErrorResult)serializer.DeSerialize(df); break; case "bzip2": using (var bzs = new BZip2Stream(ms, CompressionMode.Decompress, leaveOpen: true)) errorResult = (ErrorResult)serializer.DeSerialize(bzs); break; case "lzma": using (var lzmas = new LZipStream(ms, CompressionMode.Decompress, leaveOpen: true)) errorResult = (ErrorResult)serializer.DeSerialize(lzmas); break; default: errorResult = (ErrorResult)serializer.DeSerialize(ms); break; } } //result = (TResult)serializer.DeSerialize(errorResponse.GetResponseStream()); } catch (Exception dse) { this.m_tracer.TraceError("Could not de-serialize error response! {0}", dse.Message); } Exception exception = null; if (errorResult is TResult) { exception = new RestClientException <TResult>((TResult)errorResult, e, e.Status, e.Response); } else { exception = new RestClientException <ErrorResult>((ErrorResult)errorResult, e, e.Status, e.Response); } switch (errorResponse.StatusCode) { case HttpStatusCode.Unauthorized: // Validate the response if (this.ValidateResponse(errorResponse) != ServiceClientErrorType.Valid) { throw exception; } break; case HttpStatusCode.NotModified: responseHeaders = errorResponse?.Headers; return(default(TResult)); default: throw exception; } break; case WebExceptionStatus.ConnectFailure: if ((e.InnerException as SocketException)?.SocketErrorCode == SocketError.TimedOut) { throw new TimeoutException(); } else { throw; } case WebExceptionStatus.Timeout: throw new TimeoutException(); default: throw; } } } responseHeaders = new WebHeaderCollection(); return(default(TResult)); }
public void Setter_ValidName_Success() { WebHeaderCollection w = new WebHeaderCollection(); w["Accept"] = "text/json"; }
public void HttpResponseHeader_AddInvalid_Throws(HttpResponseHeader header) { WebHeaderCollection w = new WebHeaderCollection(); Assert.Throws <IndexOutOfRangeException>(() => w[header] = "foo"); }
/// <summary> /// Parses the response. /// </summary> /// <param name="reader">The reader.</param> /// <param name="responseHeaders">Response headers</param> /// <returns>Response object.</returns> /// <remarks>If this is overriden instead of the 1-parameter version, you can read response headers</remarks> internal virtual object ParseResponse(EwsServiceXmlReader reader, WebHeaderCollection responseHeaders) { return(this.ParseResponse(reader)); }
public HttpRequestException(HttpStatusCode code, WebHeaderCollection headers) { this.statusCode = code; this.headers = headers; }
///<summary> ///初始化WebClient类 ///</summary> public WebClient() { responseHeaders = new WebHeaderCollection(); requestHeaders = new WebHeaderCollection(); }
public void Add_InvalidValue_ThrowsArgumentException(string value) { var headers = new WebHeaderCollection(); AssertExtensions.Throws <ArgumentException>("value", () => headers.Add("name", value)); }
/// <summary> /// 向服务器发送 HTTP GET 请求 /// </summary> /// <param name="url">完整的网页地址 /// <para>必须包含 "http://" 或 "https://"</para> /// </param> /// <param name="referer">参考页链接 /// <para>告知服务器, 访问时的来源地址</para> /// </param> /// <param name="allowAutoRedirect">跟随重定向响应</param> /// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns> public static byte[] Get(string url, string referer, bool allowAutoRedirect = true) { WebHeaderCollection headers = new WebHeaderCollection(); return(Get(url, referer, ref headers, allowAutoRedirect)); }
/// <summary> /// 向服务器发送 HTTP GET 请求 /// </summary> /// <param name="url">完整的网页地址 /// <para>必须包含 "http://" 或 "https://"</para> /// </param> /// <param name="referer">参考页链接 /// <para>告知服务器, 访问时的来源地址</para> /// </param> /// <param name="cookies">请求附带的 Cookies /// <para>此参数支持自动更新 <see cref="CookieContainer"/>, 若 <see cref="AutoCookieMerge"/> 参数为 True, 将合并新旧 Cookie</para> /// </param> /// <param name="headers">请求附带的 Headers /// <para>此参数支持自动更新 <see cref="WebHeaderCollection"/></para> /// </param> /// <param name="allowAutoRedirect">跟随重定向响应</param> /// <param name="autoCookieMerge">指定自动 <see cref="CookieContainer"/> 合并</param> /// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns> public static byte[] Get(string url, string referer, ref CookieCollection cookies, bool allowAutoRedirect = true, bool autoCookieMerge = true) { WebHeaderCollection headers = new WebHeaderCollection(); return(Get(url, referer, ref cookies, ref headers, null, Encoding.UTF8, allowAutoRedirect, autoCookieMerge)); }
/// <summary> /// 向服务器发送 HTTP GET 请求 /// </summary> /// <param name="url">完整的网页地址 /// <para>必须包含 "http://" 或 "https://"</para> /// </param> /// <param name="referer">参考页链接 /// <para>告知服务器, 访问时的来源地址</para> /// </param> /// <param name="cookies">请求附带的 Cookies /// <para>此参数支持自动更新 <see cref="CookieContainer"/>, 若 <see cref="AutoCookieMerge"/> 参数为 True, 将合并新旧 Cookie</para> /// </param> /// <param name="headers">请求附带的 Headers /// <para>此参数支持自动更新 <see cref="WebHeaderCollection"/></para> /// </param> /// <param name="proxy">代理 <see cref="HttpWebClient"/> 的 <see cref="WebProxy"/> 实例</param> /// <param name="encoding">文本编码</param> /// <param name="allowAutoRedirect">跟随重定向响应</param> /// <param name="autoCookieMerge">指定自动 <see cref="CookieContainer"/> 合并</param> /// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns> public static byte[] Get(string url, string referer, ref CookieCollection cookies, ref WebHeaderCollection headers, WebProxy proxy, Encoding encoding, bool allowAutoRedirect = true, bool autoCookieMerge = true) { return(Get(url, referer, string.Empty, string.Empty, 0, ref cookies, ref headers, proxy, encoding, allowAutoRedirect, autoCookieMerge)); }
public void Remove_InvalidHeader_ThrowsArgumentException(string name) { var headers = new WebHeaderCollection(); AssertExtensions.Throws <ArgumentException>("name", () => headers.Remove(name)); }
public void Setter_ValidValue_Success(string value) { WebHeaderCollection w = new WebHeaderCollection(); w["custom"] = value; }
public void Setter_InvalidName_Throws(string name) { WebHeaderCollection w = new WebHeaderCollection(); AssertExtensions.Throws <ArgumentException>("name", () => w[name] = "test"); }
public void HttpRequestHeader_IsRestricted_Success() { Assert.True(WebHeaderCollection.IsRestricted("Accept")); Assert.False(WebHeaderCollection.IsRestricted("Age")); Assert.False(WebHeaderCollection.IsRestricted("Accept", true)); }
public void Setter_InvalidValue_Throws(string value) { WebHeaderCollection w = new WebHeaderCollection(); AssertExtensions.Throws <ArgumentException>("value", () => w["custom"] = value); }
public void Add_NullName_ThrowsArgumentNullException() { var headers = new WebHeaderCollection(); AssertExtensions.Throws <ArgumentNullException>("name", () => headers.Add(null, "value")); }
void Init() { headers = new WebHeaderCollection (); keep_alive = true; status_code = 200; status_description = "OK"; version = HttpVersion.Version11; }
public void HttpContinueMethod(int StatusCode, WebHeaderCollection httpHeaders) { }
internal ClientWebSocketOptions() { _requestedSubProtocols = new List <string>(); _requestHeaders = new WebHeaderCollection(); }
public void ToString_Empty_Success() { WebHeaderCollection w = new WebHeaderCollection(); Assert.Equal("\r\n", w.ToString()); }
/// <summary> /// 向服务器发送 HTTP GET 请求 /// </summary> /// <param name="url">完整的网页地址 /// <para>必须包含 "http://" 或 "https://"</para> /// </param> /// <param name="headers">请求附带的 Headers /// <para>此参数支持自动更新 <see cref="WebHeaderCollection"/></para> /// </param> /// <param name="allowAutoRedirect">跟随重定向响应</param> /// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns> public static byte[] Get(string url, ref WebHeaderCollection headers, bool allowAutoRedirect = true) { CookieCollection cookies = new CookieCollection(); return(Get(url, string.Empty, ref cookies, ref headers, null, Encoding.UTF8, allowAutoRedirect, false)); }
public void Add_NullHeader_ThrowsArgumentNullException(string header) { var headers = new WebHeaderCollection(); AssertExtensions.Throws <ArgumentNullException>("header", () => headers.Add(header)); }
public void ResponseHeader_QueryRequest_Fail() { WebHeaderCollection w = new WebHeaderCollection(); w[HttpResponseHeader.ContentLength] = "123"; Assert.Throws<InvalidOperationException>(() => w[HttpRequestHeader.Accept]); }
/// <summary> /// 向服务器发送 HTTP POST 请求 /// </summary> /// <param name="url">完整的网页地址 /// <para>必须包含 "http://" 或 "https://"</para> /// </param> /// <param name="data">请求所需的上传数据</param> /// <param name="contentType">Content-Type HTTP 标头</param> /// <param name="referer">参考页链接 /// <para>告知服务器, 访问时的来源地址</para> /// </param> /// <param name="userAgent">User-Agent HTTP 标头</param> /// <param name="accept">Accept HTTP 标头</param> /// <param name="timeout">超时时间</param> /// <param name="cookies">请求附带的 Cookies /// <para>此参数支持自动更新 <see cref="CookieContainer"/>, 若 <see cref="AutoCookieMerge"/> 参数为 True, 将合并新旧 Cookie</para> /// </param> /// <param name="headers">请求附带的 Headers /// <para>此参数支持自动更新 <see cref="WebHeaderCollection"/></para> /// </param> /// <param name="proxy">代理 <see cref="HttpWebClient"/> 的 <see cref="WebProxy"/> 实例</param> /// <param name="encoding">文本编码</param> /// <param name="allowAutoRedirect">跟随重定向响应</param> /// <param name="autoCookieMerge">指定自动 <see cref="CookieContainer"/> 合并</param> /// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns> public static byte[] Post(string url, byte[] data, string contentType, string referer, string userAgent, string accept, int timeout, ref CookieCollection cookies, ref WebHeaderCollection headers, WebProxy proxy, Encoding encoding, bool allowAutoRedirect = true, bool autoCookieMerge = true) { HttpWebClient httpWebClient = new HttpWebClient(); httpWebClient.ContentType = contentType; httpWebClient.Referer = referer; httpWebClient.UserAgent = userAgent; httpWebClient.Accept = accept; httpWebClient.TimeOut = timeout; httpWebClient.CookieCollection = cookies; httpWebClient.Headers = headers; httpWebClient.Proxy = proxy; httpWebClient.AutoCookieMerge = autoCookieMerge; httpWebClient.AllowAutoRedirect = allowAutoRedirect; byte[] result = httpWebClient.UploadData(new Uri(url), data); headers = httpWebClient.ResponseHeaders; cookies = httpWebClient.CookieCollection; return(result); }
public ChunkStream(byte[] buffer, int offset, int size, WebHeaderCollection headers) : this(headers) { Write(buffer, offset, size); }
/// <summary> /// 向服务器发送 HTTP POST 请求 /// </summary> /// <param name="url">完整的网页地址 /// <para>必须包含 "http://" 或 "https://"</para> /// </param> /// <param name="data">请求所需的上传数据</param> /// <param name="contentType">Content-Type HTTP 标头</param> /// <param name="referer">参考页链接 /// <para>告知服务器, 访问时的来源地址</para> /// </param> /// <param name="cookies">请求附带的 Cookies /// <para>此参数支持自动更新 <see cref="CookieContainer"/>, 若 <see cref="AutoCookieMerge"/> 参数为 True, 将合并新旧 Cookie</para> /// </param> /// <param name="headers">请求附带的 Headers /// <para>此参数支持自动更新 <see cref="WebHeaderCollection"/></para> /// </param> /// <param name="allowAutoRedirect">跟随重定向响应</param> /// <param name="autoCookieMerge">指定自动 <see cref="CookieContainer"/> 合并</param> /// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns> public static byte[] Post(string url, byte[] data, string contentType, string referer, ref CookieCollection cookies, ref WebHeaderCollection headers, bool allowAutoRedirect = true, bool autoCookieMerge = true) { return(Post(url, data, contentType, referer, ref cookies, ref headers, Encoding.UTF8, allowAutoRedirect, autoCookieMerge)); }
internal HttpListenerRequest(HttpListenerContext context) { this.context = context; headers = new WebHeaderCollection(); version = HttpVersion.Version10; }
/// <summary> /// 向服务器发送 HTTP POST 请求 /// </summary> /// <param name="url">完整的网页地址 /// <para>必须包含 "http://" 或 "https://"</para> /// </param> /// <param name="data">请求所需的上传数据</param> /// <param name="contentType">Content-Type HTTP 标头</param> /// <param name="referer">参考页链接 /// <para>告知服务器, 访问时的来源地址</para> /// </param> /// <param name="headers">请求附带的 Headers /// <para>此参数支持自动更新 <see cref="WebHeaderCollection"/></para> /// </param> /// <param name="allowAutoRedirect">跟随重定向响应</param> /// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns> public static byte[] Post(string url, byte[] data, string contentType, string referer, ref WebHeaderCollection headers, bool allowAutoRedirect = true) { CookieCollection cookies = new CookieCollection(); return(Post(url, data, contentType, referer, ref cookies, ref headers, allowAutoRedirect, false)); }
public static void Headers_Roundtrips() { var wc = new WebClient(); Assert.NotNull(wc.Headers); Assert.Empty(wc.Headers); wc.Headers = null; Assert.NotNull(wc.Headers); Assert.Empty(wc.Headers); var whc = new WebHeaderCollection(); wc.Headers = whc; Assert.Same(whc, wc.Headers); }
/// <summary> /// 向服务器发送 HTTP POST 请求 /// </summary> /// <param name="url">完整的网页地址 /// <para>必须包含 "http://" 或 "https://"</para> /// </param> /// <param name="data">请求所需的上传数据</param> /// <param name="contentType">Content-Type HTTP 标头</param> /// <param name="headers">请求附带的 Headers /// <para>此参数支持自动更新 <see cref="WebHeaderCollection"/></para> /// </param> /// <param name="allowAutoRedirect">跟随重定向响应</param> /// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns> public static byte[] Post(string url, byte[] data, string contentType, ref WebHeaderCollection headers, bool allowAutoRedirect = true) { return(Post(url, data, contentType, string.Empty, ref headers, allowAutoRedirect)); }
internal HeartbeatSentEventArgs( HeartbeatData heartbeatData, WebHeaderCollection headers, HttpStatusCode status, string text ) { HeartbeatData = heartbeatData; ResponseHeaders = headers; ResponseStatusCode = status; ResponseText = text; }
/// <summary> /// 向服务器发送 HTTP POST 请求 /// </summary> /// <param name="url">完整的网页地址 /// <para>必须包含 "http://" 或 "https://"</para> /// </param> /// <param name="data">请求所需的上传数据</param> /// <param name="contentType">Content-Type HTTP 标头</param> /// <param name="referer">参考页链接 /// <para>告知服务器, 访问时的来源地址</para> /// </param> /// <param name="allowAutoRedirect">跟随重定向响应</param> /// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns> public static byte[] Post(string url, byte[] data, string contentType, string referer, bool allowAutoRedirect = true) { WebHeaderCollection headers = new WebHeaderCollection(); return(Post(url, data, contentType, referer, ref headers, allowAutoRedirect)); }
private void ResponseCallback(IAsyncResult asynchronousResult) { _responseCallbackCallCount++; try { using (HttpWebResponse response = (HttpWebResponse)_savedHttpWebRequest.EndGetResponse(asynchronousResult)) { _savedResponseHeaders = response.Headers; } } catch (Exception ex) { _savedResponseException = ex; } }
/** * get 请求 * uri: 请求相对路径 * param:请求参数 * */ protected HttpResponse <T> Get <T>(String uri, Dictionary <String, Object> param, WebHeaderCollection headers) { String requestUri = this.uri + uri + "?"; if (param != null) { foreach (KeyValuePair <String, Object> entry in param) { requestUri += entry.Value + "=" + entry.Value.ToString(); requestUri += "&"; } } WebRequest request = WebRequest.Create(requestUri); request.Method = "GET"; request.ContentType = "application/json; charset=utf-8"; if (headers != null) { request.Headers = headers; } String resultString = String.Empty; HttpWebResponse response; try { using (response = (HttpWebResponse)request.GetResponse()) { Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); resultString = reader.ReadToEnd(); reader.Close(); dataStream.Close(); } } catch (WebException exp) { response = (HttpWebResponse)exp.Response; } return(new HttpResponse <T>(response, resultString)); }
public ChunkStream(byte[] buffer, int offset, int count, WebHeaderCollection headers) : this(headers) { Write (buffer, offset, count); }
public MockRequestChannel AddReturnObject(object response, WebHeaderCollection responseHeaders) { return(this.AddReturnObject(new List <object> { response }, responseHeaders)); }