public EndGetResponse ( System asyncResult ) : System.Net.WebResponse | ||
asyncResult | System | |
리턴 | System.Net.WebResponse |
private ServiceResponse SendRequestAsyncTPL(WebRequest request) { return _retryPolicy.ExecuteAction<ServiceResponse>(() => { var task = Task.Factory.FromAsync( request.BeginGetResponse, asyncResult => request.EndGetResponse(asyncResult), null) .ContinueWith((t) => { var response = (HttpWebResponse)t.Result; var reader = new StreamReader(response.GetResponseStream()); var message = reader.ReadToEnd(); return new ServiceResponse() { IsSuccess = true, Message = message }; }); try { return task.Result; } catch (AggregateException ae) { throw MappedAggregateException(ae); } }); }
public override WebResponse EndGetResponse(IAsyncResult asyncResult) { var response = _internalWebRequest.EndGetResponse(asyncResult); if (response.Headers[HttpRequestHeader.ContentEncoding] == "gzip" && response is HttpWebResponse) { return(new GZipWebResponse(response as HttpWebResponse)); } else { return(response); } }
XElement ToXml(WebRequest request, IAsyncResult result) { if (result.IsCompleted) { using (var response = request.EndGetResponse(result)) using (var input = response.GetResponseStream()) { return ToXml(input); } } return null; }
private string ReadResult(WebRequest webRequest, IAsyncResult asyncResult) { try { using (var response = webRequest.EndGetResponse(asyncResult)) { var result = response.GetResponseString(); return result; } } catch { return "Error"; } }
private void GeneralProcessResponse(WebRequest request, IAsyncResult result, Action<Stream> responseStreamHandler) { IsLoading = false; try { var response = request.EndGetResponse(result); using (var stream = response.GetResponseStream()) { responseStreamHandler(stream); } } catch (Exception exception) { ReportError("Sorry - problem seen " + exception.Message); } }
private static void RequestAsync(WebRequest request, byte[] bodyBytes, Action<TrackResult> callback) { request.BeginGetRequestStream((r1) => { try { var stream = request.EndGetRequestStream(r1); stream.BeginWrite(bodyBytes, 0, bodyBytes.Length, (r2) => { try { stream.EndWrite(r2); stream.Dispose(); request.BeginGetResponse((r3) => { try { using (var response = request.EndGetResponse(r3)) { using (var reader = new StreamReader(response.GetResponseStream())) { if (callback != null) callback(new TrackResult(reader.ReadToEnd())); } } } catch (Exception ex) { HandleError(callback, ex); } }, null); } catch (Exception ex) { HandleError(callback, ex); } }, null); } catch(Exception ex) { HandleError(callback, ex); } }, null); }
private static WebResponse GetResponseInternal(WebRequest request) { // build the envent using (var revent = new ManualResetEvent(false)) { // start the async call IAsyncResult result = request.BeginGetResponse(new AsyncCallback(CallStreamCallback), revent); // wait for event revent.WaitOne(); // get the response WebResponse response = request.EndGetResponse(result); // go ahead return response; } }
/// <summary> /// This sets the event handler with request and response data and /// translates storage exceptions. /// </summary> /// <param name="req">The request.</param> /// <param name="asyncResult">The async result.</param> /// <param name="handler">The handler.</param> /// <param name="sender">The sender.</param> /// <returns>The processed response.</returns> internal static WebResponse ProcessWebResponse(WebRequest req, IAsyncResult asyncResult, EventHandler<ResponseReceivedEventArgs> handler, object sender) { WebResponse response = null; Exception exception = null; try { response = req.EndGetResponse(asyncResult); return response as HttpWebResponse; } catch (WebException e) { response = e.Response; exception = Utilities.TranslateWebException(e); throw exception; } finally { EventHelper.OnResponseReceived(req, response, handler, sender, exception); } }
private void ProcessResponse(WebRequest request, IAsyncResult result) { try { var fileService = MvxFileStoreHelper.SafeGetFileStore(); var tempFilePath = DownloadPath + ".tmp"; using (var resp = request.EndGetResponse(result)) { using (var s = resp.GetResponseStream()) { fileService.WriteFile(tempFilePath, fileStream => { var buffer = new byte[4 * 1024]; int count; while ((count = s.Read(buffer, 0, buffer.Length)) > 0) { fileStream.Write(buffer, 0, count); } }); } } fileService.TryMove(tempFilePath, DownloadPath, true); } //#if !NETFX_CORE // catch (ThreadAbortException) // { // throw; // } //#endif catch (Exception exception) { FireDownloadFailed(exception); return; } FireDownloadComplete(); }
private AsyncCallback HandleResponse( WebRequest request, Uri uri, IWebAction action, byte[] content, IAuthenticator authenticator) { return ar => { try { using (var response = (HttpWebResponse) request.EndGetResponse(ar)) { using (var stream = response.GetResponseStream()) action.Complete(response.StatusCode, stream); } } catch (WebException ex) { if (authenticator != _auth) { // Another thread has already updated the authenticator Request(action, uri, content); return; } // Do we have any alternative? var next = _auth.Next(ex); _auth = next; if (next != null) Request(action, uri, content); else action.Error(ex); } }; }
private void HandleResponse(WebRequest request) { WebResponse response = null; Stream responseStream = null; StreamReader responseStreamReader = null; request.BeginGetResponse((responseResult) => { try { response = request.EndGetResponse(responseResult); responseStream = response.GetResponseStream(); responseStreamReader = new StreamReader(responseStream); ResponseText = responseStreamReader.ReadToEnd(); } finally { try { if (response != null) response.Dispose(); } catch { } try { if (responseStream != null) responseStream.Dispose(); } catch { } try { if (responseStreamReader != null) ((IDisposable)responseStreamReader).Dispose(); } catch { } DisableProgressIndicator(); } }, null); }
private void _IrosHPost(IntPtr handle, ref IrosHPostData data) { string url = Marshal.PtrToStringAnsi(data.url); string ctype = Marshal.PtrToStringAnsi(data.contentType); System.Net.WebRequest req = System.Net.WebRequest.Create(url); req.ContentType = ctype; //req.Method = data.len > 0 ? "POST" : "GET"; req.Method = "POST"; TraceLogger(String.Format("{3}ing {2} bytes to {0} handle {1}", url, handle, data.len, req.Method)); byte[] buffer = new byte[data.len]; Marshal.Copy(data.data, buffer, 0, buffer.Length); WebTask t = new WebTask() { Req = req, Handle = handle, writeBack = data.writeBack }; _http[handle] = t; AsyncCallback doResponse = ar2 => { try { var resp = req.EndGetResponse(ar2); var rs = req.GetResponse().GetResponseStream(); t.Async = rs.BeginRead(t.ReceiveBuffer, 0, t.ReceiveBuffer.Length, AsyncReceive, t); } catch (WebException e) { ErrorLogger(String.Format("Error receiving from {0}: {1}", handle, e.ToString())); t.ReceiveDone = true; if (e.Response != null) { t.Status = (int)((HttpWebResponse)e.Response).StatusCode; } else { t.Status = 500; } } catch (Exception e) { ErrorLogger(String.Format("Error receiving from {0}: {1}", handle, e.ToString())); t.ReceiveDone = true; t.Status = 500; } }; t.ReceiveBuffer = new byte[0x10000]; if (buffer.Length > 0) { t.Async = req.BeginGetRequestStream(ar => { var s = req.EndGetRequestStream(ar); using (s) { s.Write(buffer, 0, buffer.Length); } t.Completed = t.Size = buffer.Length; TraceLogger(String.Format("Beginning GetResponse for {0}", handle)); t.Async = req.BeginGetResponse(doResponse, t); }, t); } else { TraceLogger(String.Format("Beginning GetResponse [no request data] for {0}", handle)); t.Async = req.BeginGetResponse(doResponse, t); } }
BEncodedDictionary DecodeResponse(WebRequest request, IAsyncResult result) { int bytesRead = 0; int totalRead = 0; byte[] buffer = new byte[2048]; WebResponse response = request.EndGetResponse(result); using (MemoryStream dataStream = new MemoryStream(response.ContentLength > 0 ? (int)response.ContentLength : 256)) { using (BinaryReader reader = new BinaryReader(response.GetResponseStream())) { // If there is a ContentLength, use that to decide how much we read. if (response.ContentLength > 0) { while (totalRead < response.ContentLength) { bytesRead = reader.Read(buffer, 0, buffer.Length); dataStream.Write(buffer, 0, bytesRead); totalRead += bytesRead; } } else // A compact response doesn't always have a content length, so we { // just have to keep reading until we think we have everything. while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0) dataStream.Write(buffer, 0, bytesRead); } } response.Close(); dataStream.Seek(0, SeekOrigin.Begin); return (BEncodedDictionary)BEncodedValue.Decode(dataStream); } }
private static void RaiseWebResponse(WebRequest request, IAsyncResult result, Action<WebResponseEventArgs> callback) { var args = new WebResponseEventArgs {Uri = request.RequestUri}; try { var response = request.EndGetResponse(result); SetLastResponse(response); using ( var reader = new StreamReader(response.GetResponseStream())) { args.Response = reader.ReadToEnd(); } } catch (WebException ex) { args.Response = HandleWebException(ex); } callback.Invoke(args); }
private void RetornarLivrosCarregarCallback(IAsyncResult resultado) { string[] titulos = new string[6]; webRequest = resultado.AsyncState as WebRequest; if (webRequest != null) { WebResponse response = webRequest.EndGetResponse(resultado); Stream streamResponse = response.GetResponseStream(); StreamReader streamReader = new StreamReader(streamResponse); string responseString = streamReader.ReadToEnd(); if (!responseString.Contains("<!-- filename: bor-loan-no-loan-->")) { var ignored1 = activeDispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { App.ViewModel.Items.Clear(); }); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(responseString); HtmlNode table = doc.DocumentNode.Descendants().Where(n => n.Name == "table").ToList()[4]; int idCount = 0; int count = 0; foreach (HtmlNode tr in table.ChildNodes.Where(n => n.Name == "tr")) { if (count == 0) { count++; continue; } else { var ignored2 = activeDispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { App.ViewModel.Items.Add(new ItemViewModel() { Id = idCount++.ToString(), Titulo = tr.ChildNodes.Where(n => n.Name == "td").ToList()[3].InnerText, StringDevolucao = tr.ChildNodes.Where(n => n.Name == "td").ToList()[5].InnerText.Substring(0,8) }); }); } } var ignored3 = activeDispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { callbackLivros(resultado); }); } else { callbackLivros(resultado); } } else { erro = true; callbackLogin(null); } }
// Note: Adapted from OAuthWebQuery.SetAuthorizationHeader() public WebResponse GetWebResponseShim(WebRequest request, IAsyncResult result) { try { Response = request.EndGetResponse(result); return Response; } catch (WebException ex) { Exception = ex; return HandleWebException(ex); } }
private HttpWebResponse SmartGetWebResponse(WebRequest req) { try { if (req == null) return null; IAsyncResult arGet = req.BeginGetResponse(null, null); if (!arGet.AsyncWaitHandle.WaitOne(DEFAULT_READ_TIMEOUT)) { return null; } return req.EndGetResponse(arGet) as HttpWebResponse; } catch (Exception ex) { bool bShouldLog = true; WebException exw = ex as WebException; if (exw != null) { if (exw.Status == WebExceptionStatus.RequestCanceled) { bShouldLog = false; } else if (exw.Status == WebExceptionStatus.ProtocolError) { try { System.Net.HttpWebResponse httpRes = exw.Response as System.Net.HttpWebResponse; if (httpRes != null && httpRes.StatusCode == HttpStatusCode.NotFound) { SetFeedActive(false, false); FirePropertyChangedAction(false); LongSmartSleep(FEED_NOT_ACTIVE_SLEEP_SECS, "SmartGetWebResponse - Inactive Stream (404)"); // sleeping for 15 minutes on this stream! } } catch { } } } if (bShouldLog) { Common.DebugHelper.WriteExceptionToLog("WaveStreamProcessor.SmartGetWebResponse", ex, false, _streamURL); } return null; } }
protected virtual WebResponse GetWebResponse(WebRequest request, IAsyncResult result) { return(request.EndGetResponse(result)); }
private static Task<HttpWebResponse> GetResponseWithRetryAsync(WebRequest request, int retries) { if (retries < 0) throw new ArgumentOutOfRangeException("Invalid number of retries to make"); Func<Task<WebResponse>, Task<HttpWebResponse>> proceedToNextStep = null; Func<Task<HttpWebResponse>> doStep = () => { var ds = Task.Factory.FromAsync( (asyncCallback, state) => request.BeginGetResponse(asyncCallback, state), (asyncResult) => request.EndGetResponse(asyncResult), null ); return ds.ContinueWith(proceedToNextStep).Unwrap(); }; proceedToNextStep = (prevTask) => { if (prevTask.IsCanceled) throw new TaskCanceledException(); if (prevTask.IsFaulted && --retries > 0) return doStep(); var tcs = new TaskCompletionSource<HttpWebResponse>(); tcs.SetResult((HttpWebResponse)prevTask.Result); return tcs.Task; }; return doStep(); }
protected virtual WebResponse GetWebResponse (WebRequest request, IAsyncResult result) { if (abort) throw new WebException ("The operation has been aborted.", WebExceptionStatus.RequestCanceled); return request.EndGetResponse (result); }
public void LogarUsuarioCallback(IAsyncResult resultado) { try { webRequest = resultado.AsyncState as WebRequest; if (webRequest != null) { WebResponse response = (WebResponse)webRequest.EndGetResponse(resultado); Stream streamResponse = response.GetResponseStream(); StreamReader streamReader = new StreamReader(streamResponse); string responseString = streamReader.ReadToEnd(); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(responseString); HtmlNode link = doc.DocumentNode.Descendants().Where(n => n.Name == "form").FirstOrDefault(); string tokenLogin = ""; if (link != null) { tokenLogin = link.Attributes["action"].Value; tokenLogin = tokenLogin.Remove(0, tokenLogin.IndexOf("/F/") + 3); Token = tokenLogin; webRequest = WebRequest.Create(SiteAthenaLogin); webRequest.Headers["Connection"] = "Keep-Alive"; webRequest.BeginGetResponse(LoginExecutadoCallback, webRequest); } } else { erro = true; callbackLogin(null); } } catch (Exception e) { erro = true; callbackLogin(null); } }
private static void ProcessResponse(IAsyncResult asyncResult, WebRequest request, HttpResponse resp, Action<HttpResponse> action) { lock (pendingRequests) { if (pendingRequests.Contains(resp)) { pendingRequests.Remove(resp); } } try { var response = request.EndGetResponse(asyncResult); resp.IsConnected = true; var origResponse = response; using (response) { if (resp.Request.ResponseAsStream) { resp.ResponseStream = response.GetResponseStream(); } else { resp.RawResponse = response.GetResponseStream().ReadToEnd(); } if (origResponse.Headers.AllKeys.Contains("Set-Cookie")) { var cookies = origResponse.Headers["Set-Cookie"]; var index = cookies.IndexOf(';'); if (index != -1) { foreach (var c in ParseQueryString(cookies.Substring(0, index))) { resp.Cookies.Add(new Cookie(c.Key, c.Value)); } } } foreach (var key in origResponse.Headers.AllKeys) { var value = origResponse.Headers[key]; resp.Headers.Add(key, value); } } } catch (System.Exception ex) { var we = ex as WebException; if (we != null) { var temp = we.Response as HttpWebResponse; if (temp != null) { resp.HttpStatusCode = temp.StatusCode; } } if (resp.ResponseStream != null) { resp.ResponseStream.Dispose(); resp.ResponseStream = null; } resp.Exception = ex; if (action != null) { action(resp); } return; } if (action != null) { action(resp); } }
public void RenovarLivrosCarregarCallback(IAsyncResult resultado) { webRequest = resultado.AsyncState as WebRequest; if(webRequest != null) { WebResponse response = webRequest.EndGetResponse(resultado); Stream streamResponse = response.GetResponseStream(); StreamReader streamReader = new StreamReader(streamResponse); string responseString = streamReader.ReadToEnd(); if (responseString.Contains("<!--filename: bor-renew-all-body-->")) { var ignored1 = activeDispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { App.ViewModel.Items.Clear(); }); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(responseString); List<HtmlNode> node = doc.DocumentNode.Descendants().Where(n => n.Name == "table").ToList(); HtmlNode table = doc.DocumentNode.Descendants().Where(n => n.Name == "table").ToList()[3]; int idcount = 0, count =0; foreach(HtmlNode tr in table.ChildNodes.Where(n => n.Name == "tr")) { if (count == 0) { count++; continue; } else { var ignored2 = activeDispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { string motivoParaNaoRenovacao = tr.ChildNodes.Where(n => n.Name == "td").ToList()[8].InnerText; bool reservado = motivoParaNaoRenovacao.Equals("Item possui reservas."); App.ViewModel.Items.Add(new ItemViewModel() { Id = idcount++.ToString(), Reservado = reservado, Titulo = tr.ChildNodes.Where(n => n.Name == "td").ToList()[1].InnerText, StringDevolucao = tr.ChildNodes.Where(n => n.Name == "td").ToList()[3].InnerText.Substring(0,8) }); }); } } var ignored3 = activeDispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { erro = false; callbackRenovar(resultado); }); } else { erro = true; callbackRenovar(null); } } else { erro = true; callbackLogin(null); } }
int EndGetMailCount(WebRequest request) { if (currentRequestResult == null) return -1; var requestResult = currentRequestResult; currentRequestResult = null; var response = request.EndGetResponse(requestResult); using (var unreadStream = response.GetResponseStream()) { var unreadMailXmlDoc = new XmlDocument(); unreadMailXmlDoc.Load(unreadStream); var unreadMailEntries = unreadMailXmlDoc.GetElementsByTagName("entry"); return unreadMailEntries.Count; } }
private static WebResponse Nested1(IAsyncResult result, WebRequest request) { return request.EndGetResponse(result); }
private void OnGetResponseCompleted(IAsyncResult ar, WebRequest request) { Debug.Assert(ar != null); Debug.Assert(request != null); try { Debug.Assert(request != null); request.EndGetResponse(ar).Close(); // Not interested; assume OK _requests.Remove(request); } catch (Exception e) { OnWebPostError(request, e); } }
/// <include file='doc\ClientProtocol.uex' path='docs/doc[@for="WebClientProtocol.GetWebResponse1"]/*' /> /// <devdoc> /// <para> /// Gets the <see cref='System.Net.WebResponse'/> from the given request by calling /// EndGetResponse(). Derived classes can override this method to do additional /// processing on the response instance. This method is only called during /// async request processing. /// </para> /// </devdoc> protected virtual WebResponse GetWebResponse(WebRequest request, IAsyncResult result) { WebResponse response = request.EndGetResponse(result); #if !MONO if (response != null && debugger != null) debugger.NotifyClientCallReturn(response); #endif return response; }
private static void PostRequest(WebRequest request, IAsyncResult ar, byte[] data) { using (var output = request.EndGetRequestStream(ar)) { output.Write(data, 0, data.Length); } request.BeginGetResponse(ErrorReportingAsyncCallback(rar => request.EndGetResponse(rar).Close()), null); }
void LoginExecutadoCallback(IAsyncResult resultado) { try { webRequest = resultado.AsyncState as WebRequest; if (webRequest != null) { WebResponse response = webRequest.EndGetResponse(resultado); Stream responseStream = response.GetResponseStream(); StreamReader responseStreamReader = new StreamReader(responseStream); string responseString = responseStreamReader.ReadToEnd(); if (responseString.Contains("<!-- filename: login-session-uep01 -->")) { erro = true; dadosIncorretos = true; callbackLogin(null); } else { erro = false; dadosIncorretos = false; callbackLogin(resultado); } } else { erro = true; callbackLogin(null); } } catch (Exception e) { erro = true; callbackLogin(null); } }
protected virtual WebResponse GetWebResponse (WebRequest request, IAsyncResult result) { WebResponse response = request.EndGetResponse (result); responseHeaders = response.Headers; return response; }
internal static WebResponse EndGetResponse(WebRequest request, IAsyncResult ar) { WebResponse response = request.EndGetResponse(ar); if (response is HttpWebResponse && !(request is HttpWebRequest)) throw new ArgumentException(); // It is not clear whether WebRequest.GetRespone() can ever return null, but some of the v1 code had // this check, so it is added here just in case. if (response == null) { Uri requestUri = BaseUriHelper.PackAppBaseUri.MakeRelativeUri(request.RequestUri); throw new IOException(SR.Get(SRID.GetResponseFailed, requestUri.ToString())); } HandleWebResponse(response); return response; }
/// <summary> /// /// </summary> /// <param name="request"></param> /// <param name="result"></param> /// <returns></returns> protected virtual WebResponse GetWebResponse(WebRequest request, IAsyncResult result) { return request.EndGetResponse(result); }
/// <summary> /// Callback used to process server response for download WebRequest. /// </summary> /// <param name="result">Server response state.</param> protected void DownloadCallback(IAsyncResult result) { if (_aborted) { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { _downloadStatus.ProgressBar.IsEnabled = false; }); _aborted = false; return; } try { _request = (WebRequest)result.AsyncState; var response = (WebResponse)_request.EndGetResponse(result); using (var stream = response.GetResponseStream()) using (var reader = new StreamReader(stream)) { var contents = reader.ReadToEnd(); contents = contents.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>", ""); contents = string.Format("<surveys>{0}</surveys>", contents); XDocument documentXML = XDocument.Parse(contents); XElement root = documentXML.Element("surveys"); var surveys = from survey in root.Descendants("survey") select survey; List<XDocument> surveyXDocuments = new List<XDocument>(); if (_downloadStatus.IsCanceled) { return; } foreach (XElement survey in surveys) { if (_operationsOnList.IsSurveySaved(survey.Attribute("id").Value)) { continue; } XDocument doc = new XDocument(); doc.Add(survey); surveyXDocuments.Add(doc); } if (_surveysToDownload.Count == surveyXDocuments.Count) { bool canISave = true; foreach (XDocument doc in surveyXDocuments) { XElement surveyRoot = doc.Element("survey"); var isInListToDownload = from survey in _surveysToDownload where survey.SurveyId == surveyRoot.Attribute("id").Value select survey; if (isInListToDownload.Count<SurveyBasicInfo>() != 1) { canISave = false; break; } } if (canISave) { if (_downloadStatus.IsCanceled) { return; } _downloadStatus.CanCancel = false; try { foreach (XDocument surveyDocument in surveyXDocuments) { SaveSurvey(surveyDocument); } System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { _operationsOnList.Add(_surveysToDownload); }); SendAcknowledge(); } catch (IsolatedStorageException) { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { _downloadStatus.ProgressBar.IsEnabled = false; _downloadStatus.Message.Show(Languages.AppResources.downloadNewSurveys_SavingProblem); _downloadStatus.CanCancel = true; }); } } else { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { _downloadStatus.ProgressBar.IsEnabled = false; _downloadStatus.Message.Show(Languages.AppResources.downloadNewSurveys_WrongResponse); }); } } else { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { _downloadStatus.ProgressBar.IsEnabled = false; _downloadStatus.Message.Show(Languages.AppResources.downloadNewSurveys_MoreSurveys); }); } } } catch (WebException) { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { _downloadStatus.ProgressBar.IsEnabled = false; _downloadStatus.Message.Show(Languages.AppResources.checkForNewSurveyList_ServerNotFound); }); } catch (XmlException) { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { _downloadStatus.ProgressBar.IsEnabled = false; _downloadStatus.Message.Show(Languages.AppResources.checkForNewSurveyList_ServerIncompleteResponse); }); } }