当前位置: 首页>>代码示例>>C#>>正文


C# HttpWebRequest.EndGetResponse方法代码示例

本文整理汇总了C#中System.Net.HttpWebRequest.EndGetResponse方法的典型用法代码示例。如果您正苦于以下问题:C# HttpWebRequest.EndGetResponse方法的具体用法?C# HttpWebRequest.EndGetResponse怎么用?C# HttpWebRequest.EndGetResponse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.HttpWebRequest的用法示例。


在下文中一共展示了HttpWebRequest.EndGetResponse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetResponseAsync

        public Task<WebResponse> GetResponseAsync(HttpWebRequest request, int timeoutMs)
        {
            if (timeoutMs > 0)
            {
                return GetResponseAsync(request, TimeSpan.FromMilliseconds(timeoutMs));
            }

            var tcs = new TaskCompletionSource<WebResponse>();

            try
            {
                request.BeginGetResponse(iar =>
                {
                    try
                    {
                        var response = (HttpWebResponse)request.EndGetResponse(iar);
                        tcs.SetResult(response);
                    }
                    catch (Exception exc)
                    {
                        tcs.SetException(exc);
                    }
                }, null);
            }
            catch (Exception exc)
            {
                tcs.SetException(exc);
            }

            return tcs.Task;
        }
开发者ID:daltekkie,项目名称:Emby.ApiClient,代码行数:31,代码来源:PortableHttpWebRequestFactory.cs

示例2: AsyncGetResponse

        /// <summary>
        /// Encapsulates GetResponse so tests don't invoke the request
        /// </summary>
        /// <param name="req">Request to Twitter</param>
        /// <returns>Response to Twitter</returns>
        public static HttpWebResponse AsyncGetResponse(HttpWebRequest req)
        {
            Exception asyncException = null;

            var resetEvent = new ManualResetEvent(/*initialStateSignaled:*/ false);
            HttpWebResponse res = null;

            req.BeginGetResponse(
                new AsyncCallback(
                    ar =>
                    {
                        try
                        {
                            res = req.EndGetResponse(ar) as HttpWebResponse;
                        }
                        catch (Exception ex)
                        {
                            asyncException = ex;
                        }
                        finally
                        {
                            resetEvent.Set();
                        }
                    }), null);

            resetEvent.WaitOne();

            if (asyncException != null)
            {
                throw asyncException;
            }

            return res;
        }
开发者ID:prog-moh,项目名称:LinqToTwitter,代码行数:39,代码来源:Utilities.cs

示例3: HttpGetStreamCallback

        public void HttpGetStreamCallback(IAsyncResult asynchronousResult, HttpWebRequest request)
        {
            try{

                // End the operation
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    getAsyncSendFailResult();
                    return;
                }
                Stream streamResponse = response.GetResponseStream();
                StreamReader streamRead = new StreamReader(streamResponse);
                String responseData = streamRead.ReadToEnd();
                getConnectionReceivedHandler(responseData);

                streamResponse.Close();
                streamRead.Close();
                response.Close();
            }
            catch (Exception e)
            {
                log.errorCause( "http get failed ", e);
                getAsyncSendFailResult();
            }
        }
开发者ID:technerdlove,项目名称:SnowBallZ,代码行数:27,代码来源:NUnityNetEditor.cs

示例4: GetResponseAsynch

 private HttpWebResponse GetResponseAsynch(HttpWebRequest request)
 {
     return AsynchHelper.WaitForAsynchResponse(
         c => request.BeginGetResponse(c, null),
         (r, s) => (HttpWebResponse)request.EndGetResponse(r)
     );
 }
开发者ID:sergioazevedo,项目名称:restfulie-net,代码行数:7,代码来源:DefaultRequestDispatcher.cs

示例5: receiveHttpResonse

        public async Task<string> receiveHttpResonse(HttpWebRequest request, IAsyncResult asynchronousResult)
        {
            string responseString = String.Empty;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
            Stream streamResponse = response.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse);
            responseString = await streamRead.ReadToEndAsync();

            //var userResp = JsonConvert.DeserializeObject<T>(responseString);
            // Close the stream object

            streamRead.Close();
            streamResponse.Close();
            // Release the HttpWebResponse
            response.Close();

            HttpStatusCode responseCode = response.StatusCode;
            if (responseCode == HttpStatusCode.Created)
            {
                return Constants.SUCCESS;
            }
            else
            {
                return Constants.ERROR;
            }

        }
开发者ID:Tulika15b,项目名称:Mobile-Assignment,代码行数:27,代码来源:HttpServiceRequestClass.cs

示例6: IssueRequest

        public static IEnumerator<object> IssueRequest(HttpWebRequest request)
        {
            var fResponse = new Future<HttpWebResponse>();
            ThreadPool.QueueUserWorkItem(
                (__) => {
                    try {
                        request.BeginGetResponse(
                            (ar) => {
                                try {
                                    var _ = (HttpWebResponse)request.EndGetResponse(ar);
                                    fResponse.SetResult(_, null);
                                } catch (Exception ex) {
                                    fResponse.SetResult(null, ex);
                                }
                            }, null
                        );
                    } catch (Exception ex_) {
                        fResponse.SetResult(null, ex_);
                    }
                }
            );

            yield return fResponse;
            if (fResponse.Failed)
                throw new RequestFailedException(fResponse.Error);

            using (var response = fResponse.Result) {
                var fResponseStream = Future.RunInThread(
                    () => response.GetResponseStream()
                );
                yield return fResponseStream;

                Encoding encoding = AsyncTextReader.DefaultEncoding;
                if (!string.IsNullOrEmpty(response.CharacterSet))
                    encoding = Encoding.GetEncoding(response.CharacterSet);

                string responseText;
                using (var stream = fResponseStream.Result)
                using (var adapter = new AsyncTextReader(new StreamDataAdapter(stream, false), encoding)) {
                    var fText = adapter.ReadToEnd();

                    yield return fText;

                    responseText = fText.Result;
                }

                var cookies = new Cookie[response.Cookies.Count];
                response.Cookies.CopyTo(cookies, 0);

                yield return new Result(new Response {
                    Body = responseText,
                    ContentType = response.ContentType,
                    StatusCode = response.StatusCode,
                    StatusDescription = response.StatusDescription,
                    Cookies = cookies
                });
            }
        }
开发者ID:pakoito,项目名称:Fracture,代码行数:58,代码来源:Web.cs

示例7: Map

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="request"></param>
        /// <param name="result"></param>
        /// <param name="statusCode"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public Attachment Map(string key, HttpWebRequest request, IAsyncResult result, out HttpStatusCode statusCode,
                              out Exception exception)
        {
            try
            {
                var response = request.EndGetResponse(result) as HttpWebResponse;
                Stream stream = response.GetResponseStream();

                statusCode = response.StatusCode;
                exception = null;

                var headers = new NameValueCollection();
                foreach (string headerKey in response.Headers.AllKeys)
                {
                    headers.Add(headerKey, response.Headers[key]);
                }

                return new Attachment
                           {
                               Data = stream.ReadData(),
                               Etag = new Guid(response.Headers["ETag"]),
                               Metadata = headers.FilterHeaders(isServerDocument: false)
                           };
            }
            catch (WebException ex)
            {
                var httpWebResponse = ex.Response as HttpWebResponse;
                if (httpWebResponse == null)
                {
                    throw;
                }

                statusCode = httpWebResponse.StatusCode;
                exception = AsyncServerClient.ExtractException(httpWebResponse);

                if (httpWebResponse.StatusCode == HttpStatusCode.Conflict)
                {
                    JObject conflictsDoc = JObject.Load(new BsonReader(httpWebResponse.GetResponseStream()));
                    string[] conflictIds =
                        conflictsDoc.Value<JArray>("Conflicts").Select(x => x.Value<string>()).ToArray();

                    throw new ConflictException("Conflict detected on " + key +
                                                ", conflict must be resolved before the attachment will be accessible")
                              {
                                  ConflictedVersionIds = conflictIds
                              };
                }

                if (httpWebResponse.StatusCode == HttpStatusCode.NotFound)
                {
                    return null;
                }

                throw;
            }
        }
开发者ID:aduggleby,项目名称:ravendb,代码行数:65,代码来源:AttachmentMapper.cs

示例8: ResponseCallback

        private void ResponseCallback(IAsyncResult asyncResult)
        {
           webRequest = (HttpWebRequest)asyncResult.AsyncState;
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult);
            
            MemoryStream tempStream = new MemoryStream();
            webResponse.GetResponseStream().CopyTo(tempStream);

            Dispatcher.BeginInvoke(() =>
                {
                    BitmapImage image = new BitmapImage();
                    image.CreateOptions = BitmapCreateOptions.None;
                    image.SetSource(tempStream);

                    DownloadResultImage.Source = image;
                    DownloadStatusText.Text = "Download completed.";
                });
        }
开发者ID:trilok567,项目名称:Windows-Phone,代码行数:18,代码来源:GetImagePage.xaml.cs

示例9: ProcessResponse

 private void ProcessResponse(Action<List<DilbertItem>> success, Action<Exception> error, HttpWebRequest request, IAsyncResult result)
 {
     try
     {
         var response = request.EndGetResponse(result);
         using (var stream = response.GetResponseStream())
         using (var reader = new StreamReader(stream))
         {
             var text = reader.ReadToEnd();
             var list = ParseDilbertItemList(text);
             success(list);
         }
     }
     catch (Exception exception)
     {
         error(exception);
     }
 }
开发者ID:Dexyon,项目名称:MvvmCross-Samples,代码行数:18,代码来源:DilbertService.cs

示例10: GetPricesStream

        private static Stream GetPricesStream(IAsyncResult result, HttpWebRequest request)
        {
            Stream pricesStream = new MemoryStream();

            IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();

            try
            {
                // Copy resopnse to memory
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
                Stream resultStream = response.GetResponseStream();
                resultStream.CopyTo(pricesStream);
                pricesStream.Position = 0;
                resultStream.Close();

                // Copy memory to cache
                IsolatedStorageFileStream pricesCacheStream = isolatedStorage.OpenFile(PricesCacheFileName, FileMode.Create, FileAccess.Write);
                pricesStream.CopyTo(pricesCacheStream);
                pricesStream.Position = 0;
                pricesCacheStream.Close();
            }
            catch (WebException)
            {
                // If there is a problem retreiving the prices from the Internet, load the prices from the cache
                pricesStream.Close();
                if (isolatedStorage.FileExists(PricesCacheFileName))
                {
                    pricesStream = isolatedStorage.OpenFile(PricesCacheFileName, FileMode.Open, FileAccess.Read);
                }
                else
                {
                    pricesStream = null;
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("Unable to retrieve prices.");
                    });

                }
            }
            return pricesStream;
        }
开发者ID:robingrindrod,项目名称:topaz-fuel-card-windows-phone,代码行数:41,代码来源:TopazViewModel.cs

示例11: ProcessResponse

        private void ProcessResponse(Action<List<Dinner>> success, Action<Exception> error, HttpWebRequest request, IAsyncResult result)
        {
            try
            {
                var response = request.EndGetResponse(result);
                using (var stream = response.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(stream))
                    {
                        using (JsonReader reader = new JsonTextReader(sr))
                        {
                            JsonSerializer serializer = new JsonSerializer();

                            var list = serializer.Deserialize<List<Dinner>>(reader);
                            success(list);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                error(exception);
            }
        }
开发者ID:pmourfield,项目名称:NerdDinner.Apps,代码行数:24,代码来源:NerdDinnerService.cs

示例12: GetResponse

 /// <summary>
 /// Gets response text from the specified request.
 /// </summary>
 /// <param name="request">Request object.</param>
 /// <returns>Response from server.</returns>
 public string GetResponse(HttpWebRequest request, IAsyncResult result)
 {
     return ReadResponseString(request.EndGetResponse(result));
 }
开发者ID:asifhuque,项目名称:Squirrel,代码行数:9,代码来源:HttpRequestProxy.cs

示例13: GetHttpResponse

        void GetHttpResponse(HttpWebRequest request, Action<HttpResponse> callback)
        {
            request.BeginGetResponse(ar =>
                {
                    try
                    {
                        var response = (HttpWebResponse)request.EndGetResponse(ar);
                        var result = new HttpResponse();

                        using (response)
                        {
                            result.ContentType = response.ContentType;
                            result.ContentLength = response.ContentLength;
                            result.RawBytes = response.GetResponseStream().ReadAsBytes();
                            result.Content = result.RawBytes.GetString();
                            result.StatusCode = response.StatusCode;
                            result.StatusDescription = response.StatusDescription;
                            result.ResponseUri = response.ResponseUri;
                            result.ResponseStatus = ResponseStatus.Completed;

                            if (response.Cookies != null)
                            {
                                foreach (Cookie cookie in response.Cookies)
                                {
                                    result.Cookies.Add(new HttpCookie
                                    {
                                        Comment = cookie.Comment,
                                        CommentUri = cookie.CommentUri,
                                        Discard = cookie.Discard,
                                        Domain = cookie.Domain,
                                        Expired = cookie.Expired,
                                        Expires = cookie.Expires,
                                        HttpOnly = cookie.HttpOnly,
                                        Name = cookie.Name,
                                        Path = cookie.Path,
                                        Port = cookie.Port,
                                        Secure = cookie.Secure,
                                        TimeStamp = cookie.TimeStamp,
                                        Value = cookie.Value,
                                        Version = cookie.Version
                                    });
                                }
                            }

                            foreach (var headerName in response.Headers.AllKeys)
                            {
                                var headerValue = response.Headers[headerName];
                                result.Headers.Add(new HttpHeader { Name = headerName, Value = headerValue });
                            }

                            response.Close();
                        }

                        this.ExecuteCallback(result, callback);
                    }
                    catch (Exception e)
                    {
                        OnError(e, callback);
                    }


                }, null);
        }
开发者ID:koenmetsu,项目名称:XBMC.Remote,代码行数:63,代码来源:Http.cs

示例14: GetDataAsync

		private async Task<Stream> GetDataAsync( HttpWebRequest request )
		{
			Task<WebResponse> task = Task.Factory.FromAsync(
				request.BeginGetResponse,
				asyncResult =>
				{
					try
					{
						return request.EndGetResponse( asyncResult );
					}
					catch( WebException )
					{
						return null;
					}
				},
				null );

			var returnTask = await task.ContinueWith( t =>
				   ReadStreamFromResponse( t.Result ) );

			return await returnTask;
		}
开发者ID:Korshunoved,项目名称:Win10reader,代码行数:22,代码来源:FileDownloadService.cs

示例15: GetResponseCallback

 private static void GetResponseCallback(IAsyncResult asynchronousResult, HttpWebRequest request,
     string filename)
 {
     HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
     HttpStatusCode rcode = response.StatusCode;
     using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
     {
         myIsolatedStorage.DeleteFile(DIR + "\\" + filename);
     }
     SendAllExceptionsToServer(); //Keep sending files until all are submitted!
 }
开发者ID:K2DaC,项目名称:ErrBitWP,代码行数:11,代码来源:ErrBitNotify.cs


注:本文中的System.Net.HttpWebRequest.EndGetResponse方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。