private void OnStateChanged() { switch (request.ReadyState) { #region Debugging Information //case 0: // Console.WriteLine("HttpWebRequest.State 0 - Initialized"); // break; //case 1: // Console.WriteLine("HttpWebRequest.State 1 - Opened"); // break; //case 2: // Console.WriteLine("HttpWebRequest.State 2 - Send called"); // break; //case 3: // Console.WriteLine("HttpWebRequest.State 3 - Receiving data"); // break; #endregion case 4: hasResponse = true; //Console.WriteLine("========================================================="); //Console.WriteLine("==================RESPONSE RECEIVED======================"); //Console.WriteLine("{0} - Code:{1} Text:{2}", this.RequestUri.GetComponents(UriComponents.Path, UriFormat.SafeUnescaped), request.Status, request.StatusText); //Console.WriteLine("HEADERS: {0}", request.GetAllResponseHeaders()); //Console.WriteLine("RESPONSE: {0}", request.ResponseText); StreamWriter sw = new StreamWriter((Stream)null); sw.Write(request.ResponseText); var httpWebResponse = new ClientHttpWebResponse(this.Method, this.RequestUri, (HttpStatusCode)request.Status, sw.BaseStream); string responseHeaders = request.GetAllResponseHeaders(); if (responseHeaders != null) { var lines = responseHeaders.Split(new char[] { '\r' }, StringSplitOptions.RemoveEmptyEntries); foreach (var headervalue in lines) { int splitter = headervalue.IndexOf(": "); // We expect the first character to be ASCII 10 if ((int)headervalue[0] != 10 || splitter == -1) { continue; } else { string key = headervalue.Substring(1, splitter - 1); string value = headervalue.Substring(splitter + 2); httpWebResponse.Headers[key] = value; //Console.WriteLine("Key>[{0}] Value>[{1}]", key, value); } } } //Console.WriteLine("==================END-RESPONSE RECEIVED======================"); if (this.request.Status >= 300) // Error or Warning Range { resultGetResponse.SetAsCompleted(new WebException("Request failure code:" + request.Status, null, WebExceptionStatus.UnknownError, httpWebResponse), false); } else { resultGetResponse.SetAsCompleted(httpWebResponse, false); } break; } }