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); } } }
protected void PostAsync(string url, byte[] data, Action <HttpRequestResult, object> callback, object requestState, Action <HttpWebRequest> preHandler = null) { string contentType = GetContentType(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); if (preHandler != null) { preHandler(request); } request.ContentType = contentType; request.KeepAlive = true; request.Method = WebRequestMethods.Http.Post; request.ContentLength = data.Length; HttpAsyncResult httpAsyncResult = new HttpAsyncResult(callback, data, requestState); httpAsyncResult.Request = request; try { request.BeginGetRequestStream(GetRequestStreamAsyncCallback, httpAsyncResult); } catch (Exception ex) { if (callback != null) { HttpRequestResult httpRequestResult = new HttpRequestResult() { Code = -1, Data = null, Message = ex.Message }; 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); } }