void GetRequestStreamAsyncCallback(IAsyncResult ar) { HttpAsyncResult httpAsyncResult = ar.AsyncState as HttpAsyncResult; try { using (Stream requestStream = httpAsyncResult.Request.EndGetRequestStream(ar)) { requestStream.Write(httpAsyncResult.PostData, 0, httpAsyncResult.PostData.Length); requestStream.Flush(); } httpAsyncResult.Request.BeginGetResponse(new AsyncCallback(GetResponseCallback), httpAsyncResult); } catch (Exception ex) { if (httpAsyncResult.Callback != null) { HttpRequestResult httpRequestResult = new HttpRequestResult() { Code = -1, Data = null, Message = ex.Message }; httpAsyncResult.Callback(httpRequestResult, httpAsyncResult.RequestState); } } }
void GetResponseCallback(IAsyncResult ar) { HttpAsyncResult httpAsyncResult = ar.AsyncState as HttpAsyncResult; string result = null; int statusCode = -1; string message = null; try { HttpWebResponse webResponse = httpAsyncResult.Request.EndGetResponse(ar) as HttpWebResponse; using (Stream s = webResponse.GetResponseStream()) { StreamReader reader = new StreamReader(s, Encoding.UTF8); result = reader.ReadToEnd(); statusCode = (int)webResponse.StatusCode; } } catch (WebException wex) { HttpWebResponse resp = (HttpWebResponse)wex.Response; message = wex.Message; if (resp != null) { statusCode = (int)resp.StatusCode; } } catch (Exception ex) { message = ex.Message; } if (httpAsyncResult.Callback != null) { HttpRequestResult httpRequestResult = new HttpRequestResult() { Code = statusCode, Data = result, Message = message }; httpAsyncResult.Callback(httpRequestResult, httpAsyncResult.RequestState); } }