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


C# HttpRequestMessage.BeginGetResponse方法代码示例

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


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

示例1: HttpPostAsync

        /// <summary>
        /// Sends a POST request as an asynchronous operation.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="prm">The parameters.</param>
        /// <param name="authorizationHeader">The OAuth header.</param>
        /// <param name="options">The connection options for the request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// <para>The task object representing the asynchronous operation.</para>
        /// <para>The Result property on the task object returns the response.</para>
        /// </returns>
        internal static Task<AsyncResponse> HttpPostAsync(string url, IEnumerable<KeyValuePair<string, object>> prm, string authorizationHeader, ConnectionOptions options, CancellationToken cancellationToken)
        {
            if(options == null) options = new ConnectionOptions();
            if(prm == null) prm = new Dictionary<string, object>();

#if WIN_RT
            var req = new HttpRequestMessage(HttpMethod.Post, new Uri(url));
            req.Content = new HttpFormUrlEncodedContent(
                prm.Select(kvp =>new KeyValuePair<string, string>(kvp.Key, kvp.Value.ToString()))
            );
            return ExecuteRequest(req, authorizationHeader, options, cancellationToken);
#else
            var task = new TaskCompletionSource<AsyncResponse>();
            if(cancellationToken.IsCancellationRequested)
            {
                task.TrySetCanceled();
                return task.Task;
            }

            try
            {
                var req = (HttpWebRequest)WebRequest.Create(url);

                var reg = cancellationToken.Register(() =>
                {
                    task.TrySetCanceled();
                    req.Abort();
                });

                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.Headers[HttpRequestHeader.Authorization] = authorizationHeader;
#if !(PCL || WP)
                req.ServicePoint.Expect100Continue = false;
                req.ReadWriteTimeout = options.ReadWriteTimeout;
                req.Proxy = options.Proxy;
                if(options.UseCompression)
                    req.AutomaticDecompression = CompressionType;
                if (options.DisableKeepAlive)
                    req.KeepAlive = false;
#endif
#if !PCL
                req.UserAgent = options.UserAgent;
                if (options.BeforeRequestAction != null) options.BeforeRequestAction(req);
#endif

                var timeoutCancellation = new CancellationTokenSource();
                DelayAction(options.Timeout, timeoutCancellation.Token, () =>
                {
                    try
                    { 
#if PCL
                        throw new TimeoutException();
#else
                        throw new WebException("Timeout", WebExceptionStatus.Timeout);
#endif
                    }
                    catch(Exception ex)
                    {
                        task.TrySetException(ex);
                    }
                    req.Abort();
                });
                req.BeginGetRequestStream(reqStrAr =>
                {
                    try
                    {
                        var data = Encoding.UTF8.GetBytes(CreateQueryString(prm));
                        using(var stream = req.EndGetRequestStream(reqStrAr))
                            stream.Write(data, 0, data.Length);

                        req.BeginGetResponse(resAr =>
                        {
                            timeoutCancellation.Cancel();
                            reg.Dispose();
                            try
                            {
                                task.TrySetResult(new AsyncResponse((HttpWebResponse)req.EndGetResponse(resAr)));
                            }
                            catch(Exception ex)
                            {
                                task.TrySetException(ex);
                            }
                        }, null);
                    }
                    catch(Exception ex)
                    {
                        task.TrySetException(ex);
//.........这里部分代码省略.........
开发者ID:hinaloe,项目名称:CoreTweet,代码行数:101,代码来源:Request.Async.cs

示例2: HttpPostWithMultipartFormDataAsync


//.........这里部分代码省略.........
                    content.Add(new HttpStreamContent(valueInputStream), x.Key, valueStorageItem != null ? valueStorageItem.Name : "file");
                else if(valueBuffer != null)
                    content.Add(new HttpBufferContent(valueBuffer), x.Key, valueStorageItem != null ? valueStorageItem.Name : "file");
                else
                    content.Add(new HttpStringContent(x.Value.ToString()), x.Key);
            }
            cancellationToken.ThrowIfCancellationRequested();
            req.Content = content;
            return await ExecuteRequest(req, authorizationHeader, options, cancellationToken).ConfigureAwait(false);
#else
            var task = new TaskCompletionSource<AsyncResponse>();
            if(cancellationToken.IsCancellationRequested)
            {
                task.TrySetCanceled();
                return task.Task;
            }

            try
            {
                var boundary = Guid.NewGuid().ToString();
                var req = (HttpWebRequest)WebRequest.Create(url);

                var reg = cancellationToken.Register(() =>
                {
                    task.TrySetCanceled();
                    req.Abort();
                });

                req.Method = "POST";
#if !(PCL || WP)
                req.ServicePoint.Expect100Continue = false;
                req.ReadWriteTimeout = options.ReadWriteTimeout;
                req.Proxy = options.Proxy;
                req.SendChunked = true;
                if(options.UseCompression)
                    req.AutomaticDecompression = CompressionType;
                if (options.DisableKeepAlive)
                    req.KeepAlive = false;
#endif
#if !PCL
                req.UserAgent = options.UserAgent;
#endif
                req.ContentType = "multipart/form-data;boundary=" + boundary;
                req.Headers[HttpRequestHeader.Authorization] = authorizationHeader;
#if !PCL
                if(options.BeforeRequestAction != null) options.BeforeRequestAction(req);
#endif

                var timeoutCancellation = new CancellationTokenSource();
                DelayAction(options.Timeout, timeoutCancellation.Token, () =>
                {
                    try
                    {
#if PCL
                        throw new TimeoutException();
#else
                        throw new WebException("Timeout", WebExceptionStatus.Timeout);
#endif
                    }
                    catch(Exception ex)
                    {
                        task.TrySetException(ex);
                    }
                    req.Abort();
                });
                req.BeginGetRequestStream(reqStrAr =>
                {
                    try
                    {
                        using(var stream = req.EndGetRequestStream(reqStrAr))
                            WriteMultipartFormData(stream, boundary, prm);

                        req.BeginGetResponse(resAr =>
                        {
                            timeoutCancellation.Cancel();
                            reg.Dispose();
                            try
                            {
                                task.TrySetResult(new AsyncResponse((HttpWebResponse)req.EndGetResponse(resAr)));
                            }
                            catch(Exception ex)
                            {
                                task.TrySetException(ex);
                            }
                        }, null);
                    }
                    catch(Exception ex)
                    {
                        task.TrySetException(ex);
                    }
                }, null);
            }
            catch(Exception ex)
            {
                task.TrySetException(ex);
            }

            return task.Task;
#endif
        }
开发者ID:hinaloe,项目名称:CoreTweet,代码行数:101,代码来源:Request.Async.cs

示例3: HttpGetAsync

        /// <summary>
        /// Sends a GET request as an asynchronous operation.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="prm">The parameters.</param>
        /// <param name="authorizationHeader">The OAuth header.</param>
        /// <param name="options">The connection options for the request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// <para>The task object representing the asynchronous operation.</para>
        /// <para>The Result property on the task object returns the response.</para>
        /// </returns>
        internal static Task<AsyncResponse> HttpGetAsync(string url, IEnumerable<KeyValuePair<string, object>> prm, string authorizationHeader, ConnectionOptions options, CancellationToken cancellationToken)
        {
            if(options == null) options = new ConnectionOptions();
            if(prm == null) prm = new Dictionary<string, object>();
            var reqUrl = url + '?' + CreateQueryString(prm);

#if WIN_RT
            var req = new HttpRequestMessage(HttpMethod.Get, new Uri(reqUrl));
            return ExecuteRequest(req, authorizationHeader, options, cancellationToken);
#else
            var task = new TaskCompletionSource<AsyncResponse>();
            if(cancellationToken.IsCancellationRequested)
            {
                task.TrySetCanceled();
                return task.Task;
            }

            try
            {
                if(prm == null) prm = new Dictionary<string, object>();
                var req = (HttpWebRequest)WebRequest.Create(reqUrl);

                var reg = cancellationToken.Register(() =>
                {
                    task.TrySetCanceled();
                    req.Abort();
                });

#if !(PCL || WP)
                req.ReadWriteTimeout = options.ReadWriteTimeout;
                req.Proxy = options.Proxy;
                if(options.UseCompression)
                    req.AutomaticDecompression = CompressionType;
                if (options.DisableKeepAlive)
                    req.KeepAlive = false;
#endif
                req.Headers[HttpRequestHeader.Authorization] = authorizationHeader;
#if !PCL
                req.UserAgent = options.UserAgent;
                if(options.BeforeRequestAction != null) options.BeforeRequestAction(req);
#endif

                var timeoutCancellation = new CancellationTokenSource();
                DelayAction(options.Timeout, timeoutCancellation.Token, () =>
                {
                    try
                    {
#if PCL
                        throw new TimeoutException();
#else
                        throw new WebException("Timeout", WebExceptionStatus.Timeout);
#endif
                    }
                    catch(Exception ex)
                    {
                        task.TrySetException(ex);
                    }
                    req.Abort();
                });
                req.BeginGetResponse(ar =>
                {
                    timeoutCancellation.Cancel();
                    reg.Dispose();
                    try
                    {
                        task.TrySetResult(new AsyncResponse((HttpWebResponse)req.EndGetResponse(ar)));
                    }
                    catch(Exception ex)
                    {
                        task.TrySetException(ex);
                    }
                }, null);
            }
            catch(Exception ex)
            {
                task.TrySetException(ex);
            }

            return task.Task;
#endif
        }
开发者ID:hinaloe,项目名称:CoreTweet,代码行数:93,代码来源:Request.Async.cs


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