private static void OnException(StateContainer states, Exception exception) { if (exception != null) { if (states.RequesteStream != null) { states.RequesteStream.Close(); } if (states.OnError != null) { states.OnError(exception); } } }
internal static void RequestCallback(IAsyncResult result) { StateContainer states = (StateContainer)result.AsyncState; try { states.RequesteStream = states.Request.EndGetRequestStream(result); states.RequesteStream.BeginWrite(states.RequestContent, 0, states.RequestContent.Length, WriteCallback, states); } catch (Exception e) { if (states.OnError != null) { states.OnError(e); } } }
internal static void WriteCallback(IAsyncResult result) { StateContainer states = (StateContainer)result.AsyncState; try { states.RequesteStream.EndWrite(result); states.RequesteStream.Close(); states.Request.BeginGetResponse(ResponseCallback, states); } catch (Exception e) { if (states.OnError != null) { states.OnError(e); } } }
internal static void ResponseCallback(IAsyncResult result) { StateContainer states = (StateContainer)result.AsyncState; try { WebResponse response = states.Request.EndGetResponse(result); using (Stream stream = response.GetResponseStream()) { const int BufferLength = 8096; byte[] buffer = new byte[BufferLength]; string responseString; using (MemoryStream ms = new MemoryStream()) { int bytesRead; while ((bytesRead = stream.Read(buffer, 0, BufferLength)) > 0) { ms.Write(buffer, 0, bytesRead); } ms.Flush(); responseString = Encoding.UTF8.GetString(ms.ToArray()); } if (states.OnComplete != null) { states.OnComplete(responseString); } } } catch (Exception e) { if (states.OnError != null) { states.OnError(e); } } }