public void SendFile(HttpStatus httpStatus, Stream stream, string mimeType) { bool compress = MimeTypeMap.ShouldCompress(mimeType); SendHeader(httpStatus, stream.Length, mimeType, compress); Send(stream, compress); }
/// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) hashCode = hashCode * 59 + HttpStatus.GetHashCode(); hashCode = hashCode * 59 + ErrorCode.GetHashCode(); if (Description != null) { hashCode = hashCode * 59 + Description.GetHashCode(); } if (DocumentationLink != null) { hashCode = hashCode * 59 + DocumentationLink.GetHashCode(); } if (AdditionalInfo != null) { hashCode = hashCode * 59 + AdditionalInfo.GetHashCode(); } return(hashCode); } }
public HttpException(int statusCode, string statusDescription, HttpStatus status, string body, Exception ex = null) : base(ExceptionType.Http, ex) { this.HttpStatusCode = statusCode; this.StatusDescription = statusDescription; this.Status = status; this.Body = body; }
private void SendHeader(HttpStatus httpStatus, long totalBytes, string mimeType, bool compressed) { if (string.IsNullOrEmpty(mimeType)) { mimeType = "text/html"; } string statusStrng = GetHttpStatusString(httpStatus); StringBuilder header = new StringBuilder(); header.AppendFormat("HTTP/1.1 {0}\r\n", statusStrng); header.AppendFormat("Content-Type: {0}; charset=utf-8\r\n", mimeType); header.AppendFormat("Accept-Ranges: bytes\r\n"); header.AppendFormat("Server: {0}\r\n", "Web server CE"); header.AppendFormat("Connection: close\r\n"); if (!compressed) { header.AppendFormat("Content-Length: {0}\r\n", totalBytes); } if (compressed) { header.Append("Content-Encoding: deflate\r\n"); } header.Append("\r\n"); byte[] bytes = Encoding.UTF8.GetBytes(header.ToString()); if (!_tcpClient.Client.Connected) { return; } _tcpClient.GetStream().Write(bytes, 0, bytes.Length); }
/// <summary> /// 获取指定地址的资源的长度(以字节为单位)。 /// </summary> /// <param name="url">请求地址。</param> /// <returns>资源内容的长度,如果资源不存在则返回0。</returns> public static async Task <long> Head(string url) { var uri = NormalUri(url); using (var client = new HttpWebClient(m_cookieContainer)) { m_status = HttpStatus.Receiving; client.OnlyHead = true; client.UploadProgressChanged += client_UploadProgressChanged; client.UploadValuesCompleted += client_UploadValuesCompleted; client.DownloadProgressChanged += client_DownloadProgressChanged; client.DownloadDataCompleted += client_DownloadDataCompleted; try { await client.DownloadDataTaskAsync(uri); return(client.ContentLength); } catch (WebException) { return(0); } finally { m_status = HttpStatus.Ready; m_progress = 0; } } }
/// <summary> /// 从指定的地址获取包装为JSON对象的响应结果。 /// </summary> /// <param name="url"></param> /// <param name="data"></param> /// <returns></returns> public static async Task <IResult> Get(string url, IDictionary <string, object> data = null) { var uri = NormalUri(url); using (var client = new HttpWebClient(m_cookieContainer)) { m_status = HttpStatus.Receiving; client.UploadProgressChanged += client_UploadProgressChanged; client.UploadValuesCompleted += client_UploadValuesCompleted; client.DownloadProgressChanged += client_DownloadProgressChanged; client.DownloadDataCompleted += client_DownloadDataCompleted; client.Headers.Set("Accept", "application/json"); client.QueryString = UrlEncode(ToNameValueCollection(data)); if (client.QueryString != null) { Log.DebugFormat("params = {{{0}}}", string.Join(", ", client.QueryString.AllKeys .Select(_ => string.Format("{0}:{1}", _, client.QueryString[_])))); } Log.DebugFormat("receiving data from: {0}", uri); try { var content = Encoding.UTF8.GetString(await client.DownloadDataTaskAsync(uri)); return(ToResult(content)); } catch (WebException ex) { return(new JsonResult(new RpcException(ex.Response, ex))); } finally { m_status = HttpStatus.Ready; m_progress = 0; } } }
/// <summary> /// 从指定的地址获取包装为JSON对象的响应结果。 /// </summary> /// <param name="url"></param> /// <param name="method"></param> /// <param name="data"></param> /// <returns></returns> private static async Task <IResult> Execute(string url, string method, IDictionary <string, object> data = null) { var uri = NormalUri(url); method = Commons.NotBlank(method, "method").Trim().ToUpper(); using (var client = new HttpWebClient(m_cookieContainer)) { try { client.Headers.Set("Accept", "application/json"); Log.DebugFormat("sending data to: {0}", uri); m_status = HttpStatus.Sending; client.UploadProgressChanged += client_UploadProgressChanged; client.UploadValuesCompleted += client_UploadValuesCompleted; client.DownloadProgressChanged += client_DownloadProgressChanged; client.DownloadDataCompleted += client_DownloadDataCompleted; var content = Encoding.UTF8.GetString( await client.UploadValuesTaskAsync(uri, method, ToNameValueCollection(data))); Log.DebugFormat("received data: {0}", content); return(ToResult(content)); } catch (WebException ex) { return(new JsonResult(new RpcException(ex.Response, ex))); } finally { m_status = HttpStatus.Ready; m_progress = 0; } } }
private void InitOption(HttpStatus status, HttpCause cause) { this.mStatus = status; this.mCause = cause; this.mHttpErrorResponse = null; this.mWebStatus = WebExceptionStatus.Success; }
public static string Format(ushort code) { HttpStatus status = Get(code); if (status == null) { return(code + " (Unknown)"); } else { string format = code + " " + status.Message; if (status.RFC != 0) { format += " [RFC " + status.RFC + status.Section + "]"; } if (status.Info != HttpStatusInfo.None) { format += " (" + status.Info + ")"; } return(format); } }
/// <summary> /// Reads a number of bytes from the socket, as part of the message /// content. It cannot be used for reading request lines, status /// lines, or headers. /// If the reader is in an error state, this method does nothing. /// Preconditions /// buffer != null /// offset >= 0 /// count >= 0 /// offset + count lessEqual buffer.Length /// "reader is attached" /// (Status == HttpReadStatus.InContent) || "error" /// Postconditions /// if "reader was in error state when method was called" /// Result == -1 /// Status > HttpReadStatus.InContent /// if "timeout occurred" /// Result == -1 /// Status == HttpReadStatus.TimeoutError /// IOException with message == "Timeout" was thrown /// if "orderly shutdown of remote endpoint" /// Result == -1 /// Status == HttpReadStatus.ConnectionError /// if "no error occurred" /// Result >= 0 /// </summary> /// <param name="buffer">Some bytes from this buffer will be /// read</param> /// <param name="offset">Index of first byte to be read</param> /// <param name="count">Number of bytes to be read</param> /// <returns>Number of bytes actually read, /// or -1 for error</returns> public int ReadContent(byte[] buffer, int offset, int count) { Contract.Requires(buffer != null); Contract.Requires(offset >= 0); Contract.Requires(count >= 0); Contract.Requires(offset + count <= buffer.Length); Contract.Requires(connection != null); if (Status <= HttpStatus.InContent) // no error { Contract.Requires(Status == HttpStatus.InContent); if (count == 0) { return(0); } else { // count > 0 int received = connection.Read(buffer, offset, count); if (received == 0) // shutdown of remote endpoint { Status = HttpStatus.ConnectionError; return(-1); } else { Contract.Assert(received > 0); return(received); } } } else { return(-1); } }
public void StatusCheckTest_ClassUrl() { var url = new Uri("http://google.com"); var sc = new HttpStatus(url); Assert.IsTrue(sc.IsConnected); }
private void SetStatus(HttpStatus status) { if (ChangeEvent != null) { ChangeEvent(status); } }
public void StatusCheckTest_StringUrl() { var url = "http://google.com"; var sc = new HttpStatus(url); Assert.IsTrue(sc.IsConnected); }
private void CheckMessage(HttpMessage httpMessage, ExpectedMessageContainer.MessageTypes theMessageType) { try { log.DebugFormat("expectedMessageIndex {0}", expectedMessageIndex); if (expectedMessageIndex > expectedMessages.Count) { throw new System.InvalidOperationException("expectedMessageIndex " + expectedMessageIndex + " > expectedMessages.Count" + expectedMessages.Count); } ExpectedMessageContainer expectedMessage = expectedMessages[expectedMessageIndex]; Assert.True(expectedMessage.messageType == theMessageType, "Message type does not match"); // perform comparisons that are generic to all HttpMessages Assert.Equal(expectedMessage.message.HttpVersion, httpMessage.HttpVersion); // if we expected a zero length body then we expect that // the actual message has a null body since it was never set if (expectedMessage.message.Body.Length == 0) { Assert.True(httpMessage.Body == null); } else { Assert.Equal(expectedMessage.message.Body.Length, httpMessage.Body.Length); } if (theMessageType == ExpectedMessageContainer.MessageTypes.HttpRequest) { HttpRequest expected = (HttpRequest)expectedMessage.message; HttpRequest request = (HttpRequest)httpMessage; Assert.Equal(expected.Url, request.Url); Assert.Equal(expected.Method, request.Method); } else { HttpStatus expected = (HttpStatus)expectedMessage.message; HttpStatus status = (HttpStatus)httpMessage; Assert.Equal(expected.StatusCode, status.StatusCode); } // move to the next message expectedMessageIndex++; log.Debug("message matched"); } catch (System.Exception e) { // catch exceptions because the HttpSessionMonitor code will drop them log.Error("caught exception", e); Assert.True(false); } }
public static string ToStatusString(this HttpStatus status) { if (!RespStatus.ContainsKey(status)) { throw new KeyNotFoundException($"Can't found the status '{status}' in the available status string."); } return(RespStatus[status]); }
/// <summary> /// Constructor. /// </summary> /// <param name="statusCode">The status code.</param> public Error(int statusCode) { var httpStatusCode = HttpStatus.Get(statusCode); this.StatusCode = statusCode; this.Summary = httpStatusCode?.Summary; this.Description = httpStatusCode?.Description; }
/// <summary> /// Constructs a HTTP response header collection. /// </summary> /// <param name="version">HTTP protocol version.</param> /// <param name="status">HTTP response status code.</param> /// <param name="reason">Response reason phrase.</param> public HttpHeaderCollection(Version version, HttpStatus status, string reason) { this.headers = new Hashtable(); this.isRequest = true; this.version = version; this.status = status; this.reason = reason; }
/// <summary> /// Constructs a HTTP 1.1 response header collection. /// </summary> /// <param name="status">HTTP response status code.</param> /// <param name="reason">Response reason phrase.</param> public HttpHeaderCollection(HttpStatus status, string reason) { this.headers = new Hashtable(); this.isRequest = false; this.version = HttpStack.Http11; this.status = status; this.reason = reason; }
static void Main(string[] args) { HardwareStatus myComputerStatus = HardwareStatus.OK; HttpStatus websiteStatus = HttpStatus.NotFound; Console.WriteLine((int)myComputerStatus); Console.WriteLine((int)websiteStatus); }
// >> autocomplete-remote-do-in-background-xamarin protected override Java.Lang.Void RunInBackground(params string[] @params) { HttpURLConnection urlConnection = null; try { URL url = new URL ("http://www.telerik.com/docs/default-source/ui-for-ios/airports.json?sfvrsn=2"); urlConnection = (HttpURLConnection)url.OpenConnection(); urlConnection.RequestMethod = "GET"; urlConnection.UseCaches = false; urlConnection.AllowUserInteraction = false; urlConnection.Connect(); HttpStatus status = urlConnection.ResponseCode; if (status.Equals(HttpStatus.Ok)) { BufferedReader reader = new BufferedReader (new InputStreamReader(urlConnection.InputStream)); char[] buffer = new char[1024]; int n; Writer writer = new Java.IO.StringWriter(); while ((n = reader.Read(buffer)) != -1) { writer.Write(buffer, 0, n); } string json = writer.ToString(); try { JSONObject jObj = new JSONObject(json); data = jObj.GetJSONArray("airports"); } catch (JSONException ex) { ex.PrintStackTrace(); } } } catch (Java.IO.IOException e) { e.PrintStackTrace(); } finally { if (urlConnection != null) { urlConnection.Disconnect(); } } return(null); }
public override int GetHashCode() { int hash = 1; if (errorTypeCase_ == ErrorTypeOneofCase.HttpStatus) hash ^= HttpStatus.GetHashCode(); if (percentage_ != null) hash ^= Percentage.GetHashCode(); hash ^= (int) errorTypeCase_; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; }
public string GetHttpStatusString(HttpStatus httpStatus) { string result; if (!HttpStatusToString.TryGetValue(httpStatus, out result)) { result = httpStatus.ToString(); } return(string.Format("{0} {1}", (int)httpStatus, result)); }
public void HttpMonitor() { var request = new HttpStatus { Url = "http://www.microsoft.com" }; new HttpStatusMonitor().Handle(request); Assert.AreSame(State.Ok, request.State); }
/// <summary> /// Constructs a HTTP 1.1 response. /// </summary> /// <param name="status">HTTP response status code.</param> /// <param name="reason">Response reason phrase.</param> public HttpResponse(HttpStatus status, string reason) : base(status, reason) { this.parseState = ParseState.Disabled; if (content == null) { content = new BlockArray(); } }
/// <summary> /// Constructs a HTTP 1.1 response. /// </summary> /// <param name="status">HTTP response status code.</param> /// <remarks> /// The reason phrase will be initialized to the standard phrase /// from HttpStack.GetReasonPhrase(). /// </remarks> public HttpResponse(HttpStatus status) : base(status, HttpStack.GetReasonPhrase(status)) { this.parseState = ParseState.Disabled; if (content == null) { content = new BlockArray(); } }
public HttpResponse CreateResponse(HttpStatus status) { HttpResponse ret = new HttpResponse(); ret.StatusCode = status; ret.Version = Version; ret.Headers.Connection = Headers.Connection; ret.Request = this; return(ret); }
/// <summary> /// HTTP GET /// </summary> /// <param name="url"></param> /// <param name="callback"> ActionCallBack </param> /// <param name="timeout"> outTime </param> /// <param name="OnTimeout"> OnTimeOutCallBack </param> public void HttpGet(string url, Action<WWW> callback, float timeout = 0, Action<WWW> OnTimeout = null) { HttpStatus status = new HttpStatus(); StartCoroutine(Request(url, status, callback, (www) => { if (timeout > 0) { StartCoroutine(Timing(www, status, timeout, OnTimeout)); } })); }
/// <summary> /// Constructs a HTTP response. /// </summary> /// <param name="version">HTTP protocol version.</param> /// <param name="status">HTTP response status code.</param> /// <param name="reason">Response reason phrase.</param> public HttpResponse(Version version, HttpStatus status, string reason) : base(version, status, reason) { this.parseState = ParseState.Disabled; this.cbContentMax = -1; if (content == null) { content = new BlockArray(); } }
/// <summary> /// Returns a <see cref="System.String"/> that represents the current <see cref="MoBack.MoBackError"/>. /// </summary> /// <returns> Returns the error as a string. </returns> public override string ToString() { if (HttpStatus != null) { return(string.Format("Error {0}: {1}", (int)HttpStatus, HttpStatus.ToString())); } else { return("Connection Failed: " + HumanReadableConnectionStatus(ConnectionStatus)); } }
/// <summary> /// Writes a carriage return and a newline character to the /// stream. The two most recently written bytes must also /// have been a carriage return and a newline character. /// In the HTTP protocol, the sequence CR NL CR NL indicates /// the transition to the message body, i.e., the bytes /// immediately following these four bytes - if any - form the /// message content. /// This method must be cause after the last header is written /// and before the content is written! /// Preconditions /// "writer is attached" /// Status == HttpWriteStatus.BeforeContent /// Postconditions /// Status == HttpWriteStatus.InContent /// </summary> public void WriteBeginOfContent() { Contract.Requires(connection != null); Contract.Requires(Status == HttpStatus.BeforeContent); WriteChar('\r'); WriteChar('\n'); Flush(); if (Status == HttpStatus.BeforeContent) { Status = HttpStatus.InContent; } }
public async Task HttpMonitor() { var http = new HttpStatus { Url = "http://www.microsoft.com" }; var request = HealthCheckRequest.Create(http); var handler = new HTTPHealthCheck(); await handler.Handle(request, CancellationToken.None); Assert.AreSame(State.Ok, request.DataContext.State); }
/// <summary> /// HTTP GET /// </summary> /// <param name="url"></param> /// <param name="callback"> ActionCallBack </param> /// <param name="timeout"> outTime </param> /// <param name="OnTimeout"> OnTimeOutCallBack </param> public void HttpGet(string url, Action <WWW> callback, float timeout = 0, Action <WWW> OnTimeout = null) { HttpStatus status = new HttpStatus(); StartCoroutine(Request(url, status, callback, (www) => { if (timeout > 0) { StartCoroutine(Timing(www, status, timeout, OnTimeout)); } })); }
public HttpExceptionEx(HttpStatus status, HttpCause cause, string message) { this.InitOption(status, cause); try { Exception exception = new Exception(message); throw exception; } catch (Exception exception2) { this.mException = exception2; } }
public HttpExceptionEx(HttpStatus status, HttpCause cause, object baseException) { this.InitOption(status, cause); if (baseException.GetType() == typeof(WebException)) { this.mException = (WebException) baseException; this.mWebStatus = ((WebException) baseException).Status; this.mHttpErrorResponse = (HttpWebResponse) ((WebException) baseException).Response; } else { this.mException = (Exception) baseException; } }
/// <summary> /// Initializes a new instance of the <see cref="HttpResponse"/> class. /// </summary> /// <param name="source">The source.</param> internal HttpResponse(IHttpTransaction source) { if (source is HttpClient) this.client = (HttpClient)source; else this.connection = (HttpConnection)source; this.status = HttpStatus.OK; this.buffer = new MemoryStream(); this.headers = new HttpHeaderCollection(); if (source is HttpConnection) { headers["Content-Type"] = "text/html"; headers["X-Frame-Options"] = "deny"; } }
/// <summary> /// 超时 /// </summary> /// <param name="_www"></param> /// <param name="status"></param> /// <param name="timeout"></param> /// <param name="OnTimeout"></param> /// <returns></returns> IEnumerator Timing(WWW _www, HttpStatus status, float timeout, Action<WWW> OnTimeout) { yield return new WaitForSeconds(timeout); if (status.disposed || _www == null) { yield break; } if (!status.disposed || !_www.isDone) { if (OnTimeout != null) { OnTimeout(_www); } } status.disposed = true; }
IEnumerator Request(string url, HttpStatus status, WWWForm form, Action<WWW> callback, Action<WWW> OnRequestBegin = null) { using (WWW currentHttpwww = new WWW(url, form)) { if (OnRequestBegin != null) OnRequestBegin(currentHttpwww); yield return currentHttpwww; if (!status.disposed) { if (callback != null) { callback(currentHttpwww); } status.disposed = true; } } }
/// <summary> /// Read a CR-LF-terminated string from the socket. /// Postconditions /// (s == null) <=> (Status > HttpReadStatus.InContent) /// If the reader is in an error state, this method does nothing. /// </summary> /// <param name="s">String that has been read, without the /// terminating carriage return and newline characters</param> public void ReadFieldValue(out string s) { s = null; if (Status <= HttpStatus.InContent) // no error { Contract.Requires(Status == HttpStatus.BeforeContent); symbolLength = 0; char c = ReadChar(); // skip optional white space while ((Status == HttpStatus.BeforeContent) && (c == ' ')) { symbolLength = 0; c = ReadChar(); } while ((Status == HttpStatus.BeforeContent) && (c != '\r')) { c = ReadChar(); } if (Status == HttpStatus.BeforeContent) { c = ReadChar(); if (c == '\n') { if (symbolLength > symbolBufferCapacity) { // symbol too long is NOT considered as an // error in a field value, the header will // simply be skipped when the value is null } else { Contract.Assert(symbolLength >= 2); s = new string(symbolBuffer, 0, symbolLength - 2); } } else { Status = HttpStatus.SyntaxError; } } } }
/// <summary> /// Initializes a new instance of the <see cref="HttpException"/> class. /// </summary> /// <param name="message">The message.</param> /// <param name="code">The code.</param> /// <param name="innerException">The inner exception.</param> public HttpException(string message, HttpStatus code, Exception innerException) : base(message, innerException) { this.status = code; }
/// <summary> /// Attaches a writer to a socket. /// If the writer was previously used and an exception occurred, /// it can be used again anyway, because it will be completely re- /// initialized. /// Preconditions /// connection != null /// Timeout >= -1 /// Postconditions /// "writer is attached" /// </summary> /// <param name="connection">Open socket connection</param> public void Attach(Stream connection) { // Attach even works after an exception, even if the object // state is inconsistent. Contract.Requires(connection != null); Contract.Requires(Timeout >= -1); this.connection = connection; if (Timeout == 0) { Timeout = 5000; } // 5 seconds default if (connection.CanTimeout) { connection.WriteTimeout = Timeout; } Status = HttpStatus.BeforeContent; bufferPos = 0; }
/// <summary> /// Writes a carriage return and a newline character to the /// socket. The two most recently written bytes must also /// have been a carriage return and a newline character. /// In the HTTP protocol, the sequence CR NL CR NL indicates /// the transition to the message body, i.e., the bytes /// immediately following these four bytes - if any - form the /// message content. /// This method must be cause after the last header is written /// and before the content is written! /// Preconditions /// "writer is attached" /// Status == HttpWriteStatus.BeforeContent /// Postconditions /// Status == HttpWriteStatus.InContent /// </summary> public void WriteBeginOfContent() { Contract.Requires(connection != null); Contract.Requires(Status == HttpStatus.BeforeContent); WriteChar('\r'); WriteChar('\n'); Flush(); if (Status == HttpStatus.BeforeContent) { Status = HttpStatus.InContent; } }
public MemoryResponse(int statusCode) : this() { Status = new HttpStatus(statusCode, string.Empty); }
/// <summary> /// Attaches an unattached reader to a socket. /// If the reader was previously used and an exception occurred, /// it can be used again anyway, because it will be completely re- /// initialized. /// Preconditions /// connection != null /// Timeout >= -1 /// Postconditions /// "reader is attached" /// </summary> /// <param name="connection">Open socket connection</param> public void Attach(Stream connection) { Contract.Requires(connection != null); Contract.Requires(Timeout >= 0); if (Timeout == 0) { Timeout = 30000; } // 30 seconds default this.connection = connection; if (connection.CanTimeout) { connection.ReadTimeout = Timeout; } symbolLength = 0; Status = HttpStatus.BeforeContent; }
// Receive one character from socket connection. // Postconditions // (Status != HttpStatus.BeforeContent) => (Result == (char)0) // (symbolLength > symbolBufferCapacity) => "overflow" char ReadChar() { Contract.Requires(Status == HttpStatus.BeforeContent); // blocking receive operation int read = connection.Read(buffer, 0, 1); if (read == 0) // connection closed by other endpoint { Status = HttpStatus.ConnectionError; return (char)0; } var c = (char)buffer[0]; if (symbolLength < symbolBufferCapacity) { symbolBuffer[symbolLength] = c; } symbolLength = symbolLength + 1; return c; }
/// <summary> /// Initializes a new instance of the <see cref="HttpException"/> class. /// </summary> /// <param name="message">The message.</param> /// <param name="code">The code.</param> public HttpException(string message, HttpStatus code) : base(message) { this.status = code; }
/// <summary> /// Writes the status line for the given status. /// </summary> /// <param name="status">The status.</param> public void WriteStatusLine(HttpStatus status) { writer.WriteLine("HTTP/1.1 " + (int)status + " " + ResourcesProcessor.StatusStrings[(int)status]); writer.Flush(); }
/// <summary> /// Reads a number of bytes from the socket, as part of the message /// content. It cannot be used for reading request lines, status /// lines, or headers. /// If the reader is in an error state, this method does nothing. /// Preconditions /// buffer != null /// offset >= 0 /// count >= 0 /// offset + count lessEqual buffer.Length /// "reader is attached" /// (Status == HttpReadStatus.InContent) || "error" /// Postconditions /// if "reader was in error state when method was called" /// Result == -1 /// Status > HttpReadStatus.InContent /// if "timeout occurred" /// Result == -1 /// Status == HttpReadStatus.TimeoutError /// IOException with message == "Timeout" was thrown /// if "orderly shutdown of remote endpoint" /// Result == -1 /// Status == HttpReadStatus.ConnectionError /// if "no error occurred" /// Result >= 0 /// </summary> /// <param name="buffer">Some bytes from this buffer will be /// read</param> /// <param name="offset">Index of first byte to be read</param> /// <param name="count">Number of bytes to be read</param> /// <returns>Number of bytes actually read, /// or -1 for error</returns> public int ReadContent(byte[] buffer, int offset, int count) { Contract.Requires(buffer != null); Contract.Requires(offset >= 0); Contract.Requires(count >= 0); Contract.Requires(offset + count <= buffer.Length); Contract.Requires(connection != null); if (Status <= HttpStatus.InContent) // no error { Contract.Requires(Status == HttpStatus.InContent); if (count == 0) { return 0; } else { // count > 0 int received = connection.Read(buffer, offset, count); if (received == 0) // shutdown of remote endpoint { Status = HttpStatus.ConnectionError; return -1; } else { Contract.Assert(received > 0); return received; } } } else { return -1; } }
/// <summary> /// Read a blank-terminated string from the socket. /// Postconditions /// (s == null) <=> (Status > HttpReadStatus.InContent) /// If the reader is in an error state, this method does nothing. /// </summary> /// <param name="s">String that has been read, without the /// terminating blank character</param> public void ReadStringToBlank(out string s) { s = null; if (Status <= HttpStatus.InContent) // no error { Contract.Requires(Status == HttpStatus.BeforeContent); symbolLength = 0; char c = ReadChar(); while ((Status == HttpStatus.BeforeContent) && (c != ' ') && (c != '\r')) { c = ReadChar(); } if (Status == HttpStatus.BeforeContent) { if (c == ' ') // expected string terminator { if (symbolLength == 1) // empty string not allowed { Status = HttpStatus.SyntaxError; } else if (symbolLength > symbolBufferCapacity) // symbol too long { // not an error, but returned string is null } else { Contract.Assert(symbolLength > 1); s = new string(symbolBuffer, 0, symbolLength - 1); } } else { Status = HttpStatus.SyntaxError; } } } }
/// <summary> /// Read a colon-terminated string from the socket. /// The transition to reading the message content is signaled by /// returning the null string and by /// (Status == HttpReadStatus.InContent). /// Postconditions /// (s == null) => (Status > HttpReadStatus.InContent) /// If the reader is in an error state, this method does nothing. /// </summary> /// <param name="s">String that has been read, without the /// terminating colon</param> public void ReadFieldName(out string s) { s = null; if (Status <= HttpStatus.InContent) // no error { Contract.Requires(Status == HttpStatus.BeforeContent); symbolLength = 0; char c = ReadChar(); while ((Status == HttpStatus.BeforeContent) && (c != ':') && (c != '\r')) { c = ReadChar(); } if (Status == HttpStatus.BeforeContent) { if (c == ':') // expected string terminator { if (symbolLength == 1) // empty symbol not allowed { Status = HttpStatus.SyntaxError; } else if (symbolLength > symbolBufferCapacity) { // symbol too long Status = HttpStatus.SyntaxError; } else { Contract.Assert(symbolLength > 1); s = new string(symbolBuffer, 0, symbolLength - 1); } } else // not a string string, but end of headers { c = ReadChar(); if (c == '\n') { Status = HttpStatus.InContent; } else { Status = HttpStatus.SyntaxError; } } } } }