public EndGetRequestStream ( IAsyncResult asyncResult ) : Stream | ||
asyncResult | IAsyncResult | |
return | Stream |
private Stream GetRequestStreamAsynch(HttpWebRequest request) { return AsynchHelper.WaitForAsynchResponse( c => request.BeginGetRequestStream(c, null), (r, s) => request.EndGetRequestStream(r) ); }
public Task<Stream> GetRequestStreamAsync(HttpWebRequest request) { var tcs = new TaskCompletionSource<Stream>(); try { request.BeginGetRequestStream(iar => { try { var response = request.EndGetRequestStream(iar); tcs.SetResult(response); } catch (Exception exc) { tcs.SetException(exc); } }, null); } catch (Exception exc) { tcs.SetException(exc); } return tcs.Task; }
protected void POST(string URL, string post_message) { POST_REQUEST = (HttpWebRequest)HttpWebRequest.Create(URL); POST_REQUEST.Method = "POST"; POST_REQUEST.ContentType = "application/x-www-form-urlencoded"; POST_REQUEST.BeginGetRequestStream(result => { Stream post_stream = POST_REQUEST.EndGetRequestStream(result); byte[] ba = Encoding.UTF8.GetBytes(post_message); post_stream.Write(ba, 0, ba.Length); post_stream.Close(); POST_REQUEST.BeginGetResponse(new AsyncCallback(POST_Method_CallBack),POST_REQUEST); }, POST_REQUEST); }
private void RequestStreamReady(IAsyncResult ar) { string clientID = "tungnt92"; string clientSecret = "nguyentungvungocthaonguyen"; String strRequestDetails = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientID), HttpUtility.UrlEncode(clientSecret)); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)ar.AsyncState; byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strRequestDetails); System.IO.Stream postStream = request.EndGetRequestStream(ar); postStream.Write(bytes, 0, bytes.Length); postStream.Close(); request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request); }
private void BingRequestStreamReady(IAsyncResult ar) { // The request stream is ready. Write the request into the POST stream string clientID = "MacTutor"; string clientSecret = "8o5famKEXj1/RG0QV92gglvHjQZKHJjsdyw99g5EAIk="; String strRequestDetails = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", WebUtility.UrlEncode(clientID), WebUtility.UrlEncode(clientSecret)); // note, this isn't a new request -- the original was passed to beginrequeststream, so we're pulling a reference to it back out. It's the same request System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)ar.AsyncState; // now that we have the working request, write the request details into it byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strRequestDetails); System.IO.Stream postStream = request.EndGetRequestStream(ar); postStream.Write(bytes, 0, bytes.Length); postStream.Dispose(); // now that the request is good to go, let's post it to the server // and get the response. When done, the async callback will call the // GetResponseCallback function request.BeginGetResponse(new AsyncCallback(GetBingResponseCallback), request); }
private void RequestStreamData(IAsyncResult asyncResult) { try { HttpRequestState requestState = (HttpRequestState)asyncResult.AsyncState; System.Net.HttpWebRequest httpWebRequest = requestState.Request; var stream = httpWebRequest.EndGetRequestStream(asyncResult); stream.Write(requestBytes, 0, requestBytes.Length); stream.Close(); webRequest.BeginGetResponse(ReceivedData, requestState); } catch (Exception ex) { error = ex.Message; isDone = true; isError = true; responseCode = 0; } }
static void HandleGetRequestStream (IAsyncResult res, HttpWebRequest request, string body) { try { Stream s = request.EndGetRequestStream (res); using (var sw = new StreamWriter (s)) { sw.Write (body); } WebResponse resp = request.GetResponse (); s = resp.GetResponseStream (); string result; using (var sr = new StreamReader (s)) result = sr.ReadToEnd (); if (result != "OK") throw new Exception (result); } catch (Exception ex) { LoggingService.LogError ("Feedback submission failed", ex); lock (sendingLock) { sending = false; } return; } LoggingService.LogInfo ("Feedback successfully sent"); lock (sendingLock) { XmlDocument doc = LoadFeedbackDoc (); if (doc.DocumentElement != null) { var first = doc.DocumentElement.FirstChild; doc.DocumentElement.RemoveChild (first); doc.Save (FeedbackFile); XmlElement fe = doc.DocumentElement.FirstChild as XmlElement; if (fe != null) InternalSendFeedback (fe); else sending = false; } else sending = false; } }
private void sendMessageAsync(IAsyncResult asynchronousResult, HttpWebRequest request, byte[] data, String message) { try{ // End the operation Stream postStream = request.EndGetRequestStream(asynchronousResult); postStream.Write(data, 0, data.Length); postStream.Close(); // Start the asynchronous operation to get the response request.BeginGetResponse(result => { receiveMessageAsync(result, request, message, postAsyncSendFailResult); },null); } catch ( Exception e) { log.errorCause("error while sending command " + e.Message, e); postAsyncSendFailResult(); } }
private Response DoPost(HttpWebRequest req, string postData) { Response res = null; AutoResetEvent signal = new AutoResetEvent(false); try { req.BeginGetRequestStream(reqState => { try { Stream reqStream = req.EndGetRequestStream(reqState); if (postData != null) { Encoding enc = new System.Text.UTF8Encoding(); reqStream.Write(enc.GetBytes(postData), 0, postData.Length); } reqStream.Close(); res = DoRequest(req); } catch (Exception ex) { res = new Response(-1, ex.ToString(), null); } finally { signal.Set(); } }, null); } catch (Exception ex) { res = new Response(-1, ex.ToString(), null); signal.Set(); } signal.WaitOne(); return res; }
/// <summary> /// Used by the worker thread to start the request /// </summary> public void Start() { try { // Create the request request = (HttpWebRequest)System.Net.WebRequest.Create(URL); request.Method = Method; request.Credentials = CredentialCache.DefaultCredentials; request.Proxy = null; request.KeepAlive = false; request.Timeout = (int)Math.Round((Timeout == 0f ? WebRequests.Timeout : Timeout) * 1000f); request.ServicePoint.MaxIdleTime = request.Timeout; request.ServicePoint.Expect100Continue = ServicePointManager.Expect100Continue; request.ServicePoint.ConnectionLimit = ServicePointManager.DefaultConnectionLimit; // Optional request body for post requests var data = new byte[0]; if (Body != null) { data = Encoding.UTF8.GetBytes(Body); request.ContentLength = data.Length; request.ContentType = "application/x-www-form-urlencoded"; } if (RequestHeaders != null) request.SetRawHeaders(RequestHeaders); // Perform DNS lookup and connect (blocking) if (data.Length > 0) { request.BeginGetRequestStream(result => { if (request == null) return; try { // Write request body using (var stream = request.EndGetRequestStream(result)) stream.Write(data, 0, data.Length); } catch (Exception ex) { ResponseText = ex.Message.Trim('\r', '\n', ' '); if (request != null) request.Abort(); OnComplete(); return; } WaitForResponse(); }, null); } else { WaitForResponse(); } } catch (Exception ex) { ResponseText = ex.Message.Trim('\r', '\n', ' '); Interface.Oxide.LogException(string.Format("Web request produced exception (Url: {0})", URL), ex); if (request != null) request.Abort(); OnComplete(); } }
/// <summary> /// Gets the request stream in synchronous way. /// </summary> private Stream GetRequestStream(HttpWebRequest request) { #if WINDOWS_PHONE || SILVERLIGHT _requestStreamReceived = false; IAsyncResult asyncResult; try { asyncResult = request.BeginGetRequestStream(AsyncPhoneWebRequestStreamCallback, request); } catch (SecurityException) { return null; } catch (WebException) { return null; } // HACK: take a look on comment of GetResponse() method... while (!_requestStreamReceived) { Thread.Sleep(50); } return request.EndGetRequestStream(asyncResult); #elif WINDOWS_STORE throw new NotSupportedException("Synchronous versions are not supported"); #else return request.GetRequestStream(); #endif }
private bool WriteRequestData(HttpWebRequest request, IAsyncResult asyncResult, byte[] data, int dataLength) { Stream requestStream = null; try { requestStream = asyncResult != null ? request.EndGetRequestStream(asyncResult) : GetRequestStream(request); if (requestStream == null) return true; WriteRequestData(requestStream, data, dataLength); } catch (SecurityException ex) { Event.Invoke(DataReceiveFailed, this, new HttpDataSourceEventArgs(this, HttpStatusCode.BadRequest, ex.Message)); TryCompleteRequest(request); return true; } catch (WebException ex) { if (ex.Status != WebExceptionStatus.RequestCanceled) Event.Invoke(DataReceiveFailed, this, new HttpDataSourceEventArgs(this, GetHttpStatusCode(ex.Status), ex.Message)); TryCompleteRequest(request); return true; } finally { if (requestStream != null) { #if WINDOWS_STORE requestStream.Dispose(); #else requestStream.Close(); #endif } } return false; }
private Stream GetRequestStream(HttpWebRequest req) { var asyncResult = req.BeginGetRequestStream(null, null); var hasNotTimedOut = asyncResult.AsyncWaitHandle.WaitOne(Timeout); if (!hasNotTimedOut) { // TODO: Not really an issue with the cache server. throw new CacheServerException("Could not get request stream"); } return req.EndGetRequestStream(asyncResult); }
private void LoadBodyAndSendAsync(HttpWebRequest request) { if (_bodyReader != null || _bodyString != null) { request.BeginGetRequestStream(asyncRequestStreamResult => { WriteBody(request.EndGetRequestStream(asyncRequestStreamResult)); SendAsyncRequest(request); }, null); } else { SendAsyncRequest(request); } }
private void WriteRequestBody(HttpWebRequest webRequest) { if (this.HasBody || this.HasFiles || this.AlwaysMultipartFormData) { #if !WINDOWS_PHONE #if (NETCORE50 || NETSTANDARD1_5 || NETSTANDARD1_6) #else webRequest.ContentLength = this.CalculateContentLength(); #endif #endif } #if (NETCORE50 || NETSTANDARD1_5 || NETSTANDARD1_6) var asyncResult = webRequest.BeginGetRequestStream(null, null); using (Stream requestStream = webRequest.EndGetRequestStream(asyncResult)) #else using (Stream requestStream = webRequest.GetRequestStream()) #endif { if (this.HasFiles || this.AlwaysMultipartFormData) { this.WriteMultipartFormData(requestStream); } else if (this.RequestBodyBytes != null) { requestStream.Write(this.RequestBodyBytes, 0, this.RequestBodyBytes.Length); } else if (this.RequestBody != null) { this.WriteStringTo(requestStream, this.RequestBody); } } }
/// <summary> /// Gets EndGetRequestStream implementation of the underlying HttpWebRequest class. /// </summary> public Stream EndGetRequestStream(IAsyncResult asyncResult) { return(request.EndGetRequestStream(asyncResult)); }
protected virtual void ProcessRequestThen( MvxRestRequest restRequest, HttpWebRequest httpRequest, Action continueAction, Action<Exception> errorAction) { httpRequest.BeginGetRequestStream(result => TryCatch(() => { using (var stream = httpRequest.EndGetRequestStream(result)) { restRequest.ProcessRequestStream(stream); stream.Flush(); } continueAction?.Invoke(); }, errorAction) , null); }
private static void PostWebRequest(IAsyncResult result, HttpWebRequest request, string filename) { Stream postStream = request.EndGetRequestStream(result); String post; using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile(DIR + "//" + filename, FileMode.Open); using (StreamReader reader = new StreamReader(isoFileStream)) { post = reader.ReadToEnd(); } } byte[] postBytes = Encoding.UTF8.GetBytes(post); postStream.Write(postBytes, 0, postBytes.Length); postStream.Close(); request.BeginGetResponse(res => { GetResponseCallback(res, request, filename); }, null); }
void GetRequestStream(HttpWebRequest request, Action<HttpResponse> callback) { request.BeginGetRequestStream(ar => { using (var stream = request.EndGetRequestStream(ar)) { if (HasFiles) { WriteMultipartFormData(stream); } else // This is when we have a RequestBody { stream.Write(Encoding.UTF8.GetBytes(RequestBody), 0, RequestBody.Length); } } GetHttpResponse(request, callback); }, null); }
private void WriteRequestBody(HttpWebRequest webRequest, IAsyncResult result) { if (RequestBodyBytes != null || RequestBodyString != null) { using (var requestStream = webRequest.EndGetRequestStream(result)) { if (RequestBodyBytes != null) { requestStream.Write(RequestBodyBytes, 0, RequestBodyBytes.Length); } else { WriteStringTo(requestStream, RequestBodyString); } } } }