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


C# HttpWebRequest.GetResponseAsync方法代码示例

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


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

示例1: Login

        public async Task<string> Login(string username, string password)
        {
            HttpWebRequest request = new HttpWebRequest(new Uri(String.Format("{0}Token", Constants.BaseAddress)));
            request.Method = "POST";

            string postString = String.Format("username={0}&password={1}&grant_type=password", HttpUtility.HtmlEncode(username), HttpUtility.HtmlEncode(password));
            byte[] bytes = Encoding.UTF8.GetBytes(postString);
            using (Stream requestStream = await request.GetRequestStreamAsync())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }

            try
            {
                HttpWebResponse httpResponse =  (HttpWebResponse)(await request.GetResponseAsync());
                string json;
                using (Stream responseStream = httpResponse.GetResponseStream())
                {
                    json = new StreamReader(responseStream).ReadToEnd();
                }
                TokenResponseModel tokenResponse = JsonConvert.DeserializeObject<TokenResponseModel>(json);
                return tokenResponse.AccessToken;
            }
            catch (Exception ex)
            {
                throw new SecurityException("Bad credentials", ex);
            }
        }
开发者ID:284247028,项目名称:WebAPI2AuthenticationExample,代码行数:28,代码来源:LoginService.cs

示例2: GetExternalLoginProviders

		public async Task<IEnumerable<ExternalLoginViewModel>> GetExternalLoginProviders()
		{
			string uri = String.Format("{0}/api/Account/ExternalLogins?returnUrl=%2F&generateState=true", _baseUri);
			HttpWebRequest request = new HttpWebRequest(new Uri(uri));
			request.Method = "GET";
			try
			{
				WebResponse response = await request.GetResponseAsync();
				HttpWebResponse httpResponse = (HttpWebResponse) response;
				string result;

				using (Stream responseStream = httpResponse.GetResponseStream())
				{
					result = new StreamReader(responseStream).ReadToEnd();
				}

				List<ExternalLoginViewModel> models = JsonConvert.DeserializeObject<List<ExternalLoginViewModel>>(result);
				return models;
			}
			catch (SecurityException)
			{
				throw;
			}
			catch (Exception ex)
			{
				throw new InvalidOperationException("Unable to get login providers", ex);
			}
		}
开发者ID:rioka,项目名称:WebAPI2MobileFacebookAuthentication,代码行数:28,代码来源:AuthenticationServices.cs

示例3: Register

        public async Task<bool> Register(string username, string password, string confirmPassword)
        {
            RegisterModel model = new RegisterModel
            {
                ConfirmPassword = confirmPassword,
                Password = password,
                UserName = username
            };

            HttpWebRequest request = new HttpWebRequest(new Uri(String.Format("{0}api/Account/Register", Constants.BaseAddress)));
            request.Method = "POST";
            request.ContentType = "application/json";
            request.Accept = "application/json";
            string json = JsonConvert.SerializeObject(model);
            byte[] bytes = Encoding.UTF8.GetBytes(json);
            using(Stream stream = await request.GetRequestStreamAsync())
            {
                stream.Write(bytes, 0, bytes.Length);
            }

            try
            {
                await request.GetResponseAsync();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
开发者ID:rioka,项目名称:WebAPI2AuthenticationExample,代码行数:30,代码来源:RegisterService.cs

示例4: SendAsync

        /// <summary>
        /// Queues a web request into our queue and returns an awaitable task.
        /// </summary>
        public static Task<XDocument> SendAsync(HttpWebRequest request)
        {
            lock (instance)
            {
                instance.currentTask = instance.currentTask.ContinueWith(async previousTask =>
                    {
                        var response = await request.GetResponseAsync();
                        var responseStream = response.GetResponseStream();

                        XDocument doc = null;
                        using (var streamReader = new StreamReader(responseStream))
                        {
                            string xml = await streamReader.ReadToEndAsync();
                            doc = XDocument.Parse(xml);
                        }

                        // Wait a bit to throttle the requests:
                        await Task.Delay(50);
                        return doc;

                    }).Unwrap();

                return instance.currentTask;
            }
        }
开发者ID:qwasar,项目名称:onebusaway-windows8,代码行数:28,代码来源:WebRequestQueue.cs

示例5: ConnectAsync

        public async Task<WebSocket> ConnectAsync(HttpWebRequest request, CancellationToken cancellationToken) {
            HttpWebResponse response;

            using (cancellationToken.Register(request.Abort)) {
                response = (HttpWebResponse)await request.GetResponseAsync();
            }

            InspectResponse?.Invoke(response);

            // TODO: Validate handshake
            HttpStatusCode statusCode = response.StatusCode;
            if (statusCode != HttpStatusCode.SwitchingProtocols) {
                response.Dispose();
                throw new InvalidOperationException("Incomplete handshake, invalid status code: " + statusCode);
            }
            // TODO: Validate Sec-WebSocket-Key/Sec-WebSocket-Accept

            string subProtocol = response.Headers[Constants.Headers.SecWebSocketProtocol];
            if (!string.IsNullOrEmpty(subProtocol) && !SubProtocols.Contains(subProtocol, StringComparer.OrdinalIgnoreCase)) {
                throw new InvalidOperationException("Incomplete handshake, the server specified an unknown sub-protocol: " + subProtocol);
            }

            var stream = response.GetResponseStream();

            return CommonWebSocket.CreateClientWebSocket(stream, subProtocol, KeepAliveInterval, ReceiveBufferSize, UseZeroMask);
        }
开发者ID:Microsoft,项目名称:RTVS,代码行数:26,代码来源:WebSocketClient.cs

示例6: ProcessResponse

 private static async Task<RESTResponse> ProcessResponse(HttpWebRequest request)
 {
     RESTResponse result = new RESTResponse();
     try
     {
         using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse)
         {
             result.StatusCode = (int)response.StatusCode;
             using (Stream stream = response.GetResponseStream())
             {
                 result.Content = new StreamReader(stream, System.Text.Encoding.UTF8).ReadToEnd();
             }
         }
     }
     catch (WebException ex)
     {
         if ((ex.Status == WebExceptionStatus.ProtocolError) && (ex.Response != null))
         {
             HttpWebResponse response = ex.Response as HttpWebResponse;
             result.StatusCode = (int)response.StatusCode;
             using (Stream stream = response.GetResponseStream())
             {
                 result.Content = new StreamReader(stream, System.Text.Encoding.UTF8).ReadToEnd();
             }
         }
     }
     return result;
 }
开发者ID:CreatorDev,项目名称:DeviceServer,代码行数:28,代码来源:RESTClient.cs

示例7: ExecuteRequestAsync

 public async Task<JToken> ExecuteRequestAsync(HttpWebRequest request)
 {
     EnforceRateLimit();
     var response = await request.GetResponseAsync();
     var result = await GetResponseStringAsync(response.GetResponseStream());
     return ExecuteRequestBase(result);
 }
开发者ID:txdv,项目名称:RedditSharp,代码行数:7,代码来源:WebAgentAsync.cs

示例8: GetResponseStringFromRequest

        private static async Task<string> GetResponseStringFromRequest(HttpWebRequest request)
        {
            try
            {
                using (var response = await request.GetResponseAsync()
                                                .ConfigureAwait(false))
                {
                    return GetResponseString(response);
                }
            }
            catch (WebException e)
            {
                using (var response = e.Response.GetResponseStream())
                {
                    if (response == null)
                    {
                        throw;
                    }
                    JObject responseItem;
                    try
                    {
                        responseItem = JObject.Load(new JsonTextReader(new StreamReader(response)));
                    }
                    catch (Exception)
                    {
                        throw e;
                    }
                    ThrowIfIsException(responseItem);

                    throw;
                }
            }
        }
开发者ID:rischwa,项目名称:eve-fast-fitting-assessment,代码行数:33,代码来源:CrestDocumentLoader.cs

示例9: readResponse

        private static async Task<string> readResponse(HttpWebRequest rq, string expectedContentType)
        {
            HttpWebResponse rsp;
            try
            {
                rsp = (HttpWebResponse)await rq.GetResponseAsync();
            }
            catch (WebException wex)
            {
                rsp = (HttpWebResponse)wex.Response;
            }

            if (rsp.StatusCode != HttpStatusCode.OK) Console.Error.WriteLine(rsp.StatusCode.ToString());

            string[] contentType = rsp.ContentType.Split(new string[1] { "; " }, StringSplitOptions.None);
            if (contentType[0] != expectedContentType) Console.Error.WriteLine("Received Content-Type '{0}', expected '{1}'", contentType[0], expectedContentType);

            using (var st = rsp.GetResponseStream())
                using (var tr = new StreamReader(st, Encoding.UTF8))
                {
                    string rspstr = await tr.ReadToEndAsync();
                    if (displayResponse)
                    {
                        Console.Out.WriteLineAsync(rspstr);
                    }
                    return rspstr;
                }
        }
开发者ID:JamesDunne,项目名称:ivo-cms,代码行数:28,代码来源:Program.cs

示例10: GetStringAsync

        /// <summary>
        /// GET请求
        /// </summary>
        /// <param name="url" "传入的url地址"></param>
        /// <returns></returns>
        public async Task GetStringAsync(string url)
        {
            string info = string.Empty;
            req = WebRequest.CreateHttp(url);
            req.Method = "GET";
            WebResponse res = null;
            req.ContinueTimeout = 1000;
            try
            {
                res = await req.GetResponseAsync();
               
            }
            catch (Exception e)
            {
                OnGetDataEvent(new ProgressEventArgs
                {
                    DownLoadData = null,
                    ExceptionInfo = e.Message,
                    IsComplete = false,
                    IsException = true
                });
                return;
            }
            
            //如果返回数据
            if (req.HaveResponse && null != res)
            {
                using (Stream stream = res.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        info = await reader.ReadToEndAsync();
                    }
                }
                //通知注册的事件完成下载
                OnGetDataEvent(new ProgressEventArgs
                {
                    DownLoadData = info,
                    ExceptionInfo = null,
                    IsComplete = true,
                    IsException = false
                });
            }
            else
            {
                //没有数据
                OnGetDataEvent(new ProgressEventArgs
                {
                    DownLoadData = null,
                    ExceptionInfo = null,
                    IsComplete = false,
                    IsException = true
                });
                return;
            }


        }
开发者ID:dengtuo,项目名称:XiyouLibProject,代码行数:63,代码来源:HttpWebRequestUtils.cs

示例11: GetResponseAsync

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

            return request.GetResponseAsync();
        }
开发者ID:daltekkie,项目名称:Emby.ApiClient,代码行数:9,代码来源:HttpWebRequestFactory.cs

示例12: CreateResponse

 static HttpWebResponse CreateResponse(HttpWebRequest request)
 {
     HttpWebResponse response = null;
     try
     {
         response = (HttpWebResponse)(request.GetResponseAsync().Result);
     }
     catch { }
     return response;
 }
开发者ID:WordChainGame,项目名称:Geography,代码行数:10,代码来源:WebRequests.cs

示例13: GetDownloadStreamAsync

        public Task<WebResponse> GetDownloadStreamAsync()
        {
            request = (HttpWebRequest)WebRequest.Create(
                "http://www.nicovideo.jp/api/watch/mylistvideo?id=" + id);

            request.Method = ContentMethod.Get;
            request.CookieContainer = cookieContainer;

            return request.GetResponseAsync();
        }
开发者ID:cocop,项目名称:UNicoAPI2,代码行数:10,代码来源:Accesser.cs

示例14: GetRequestStreamCallback

        private async Task GetRequestStreamCallback(Task<Stream> task, HttpWebRequest request)
        {
            Stream postStream = await task.ConfigureAwait(false);

            this.WriteMultipartObject(postStream, this.Parameters);
            postStream.Close();

            var responseTask = request.GetResponseAsync();
            await GetResponseCallback(responseTask);
        }
开发者ID:vortexwolf,项目名称:2ch-Browser-WP7,代码行数:10,代码来源:HttpPostTask.cs

示例15: _getApiResponseAsync

 private async Task<string> _getApiResponseAsync(HttpWebRequest request)
 {
     using (var response = await request.GetResponseAsync())
     {
         using (var streamReader = new StreamReader(response.GetResponseStream()))
         {
             return streamReader.ReadToEnd();
         }
     }
 }
开发者ID:WakeDown,项目名称:UnitPrinter,代码行数:10,代码来源:UnitAPI.cs


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