當前位置: 首頁>>代碼示例>>C#>>正文


C# HttpRequestMessage.EndGetResponse方法代碼示例

本文整理匯總了C#中System.Net.Http.HttpRequestMessage.EndGetResponse方法的典型用法代碼示例。如果您正苦於以下問題:C# HttpRequestMessage.EndGetResponse方法的具體用法?C# HttpRequestMessage.EndGetResponse怎麽用?C# HttpRequestMessage.EndGetResponse使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在System.Net.Http.HttpRequestMessage的用法示例。


在下文中一共展示了HttpRequestMessage.EndGetResponse方法的5個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: HttpPostWithMultipartFormDataAsync


//.........這裏部分代碼省略.........
                else
                    content.Add(new HttpStringContent(x.Value.ToString()), x.Key);
#endif
            }
            cancellationToken.ThrowIfCancellationRequested();
            req.Content = content;
            return await ExecuteRequest(client, req, authorizationHeader, options, cancellationToken).ConfigureAwait(false);
#else
            return Task.Factory.StartNew(() =>
            {
                cancellationToken.ThrowIfCancellationRequested();
                var task = new TaskCompletionSource<AsyncResponse>();

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

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

#if NET45 || WP
                req.AllowReadStreamBuffering = false;
#endif
                req.Method = "POST";
#if !(PCL || WP)
                req.ServicePoint.Expect100Continue = false;
                req.ReadWriteTimeout = options.ReadWriteTimeout;
#endif
#if !PCL
                req.UserAgent = options.UserAgent;
#endif
#if !(PCL || WP)
                req.Proxy = options.Proxy;
#endif
                req.ContentType = "multipart/form-data;boundary=" + boundary;
                req.Headers[HttpRequestHeader.Authorization] = authorizationHeader;
                cancellationToken.ThrowIfCancellationRequested();
                var memstr = new MemoryStream();
                try
                {
                    WriteMultipartFormData(memstr, boundary, prm);
                    cancellationToken.ThrowIfCancellationRequested();
#if !PCL
                    req.ContentLength = memstr.Length;
                    if(options.BeforeRequestAction != null) options.BeforeRequestAction(req);
#endif

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

                            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);
                        }
                        finally
                        {
                            memstr.Dispose();
                        }
                    }, null);

                    return task.Task;
                }
                catch
                {
                    memstr.Dispose();
                    throw;
                }
            }, cancellationToken).CheckCanceled(cancellationToken).Unwrap();
#endif
        }
開發者ID:kb10uy,項目名稱:CoreTweet,代碼行數:101,代碼來源:Request.Async.cs

示例2: 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 client = new HttpClient();
            var req = new HttpRequestMessage(HttpMethod.Post, new Uri(url));
            req.Content =
#if WIN8
                new FormUrlEncodedContent(
#else
                new HttpFormUrlEncodedContent(
#endif
                    prm.Select(kvp =>new KeyValuePair<string, string>(kvp.Key, kvp.Value.ToString()))
                );
            return ExecuteRequest(client, req, authorizationHeader, options, cancellationToken);
#else
            var task = new TaskCompletionSource<AsyncResponse>();
            if(cancellationToken.IsCancellationRequested)
            {
                task.TrySetCanceled();
                return task.Task;
            }

            try
            {
                var data = Encoding.UTF8.GetBytes(CreateQueryString(prm));
                var req = (HttpWebRequest)WebRequest.Create(url);

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

#if NET45 || WP
                req.AllowReadStreamBuffering = false;
#endif
                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;
#endif
#if !PCL
                req.UserAgent = options.UserAgent;
                req.ContentLength = data.Length;
#endif
#if !(PCL || WP)
                req.Proxy = options.Proxy;
#endif
#if !PCL
                if(options.BeforeRequestAction != null) options.BeforeRequestAction(req);
#endif

                var timeoutCancellation = new CancellationTokenSource();
                DelayAction(options.Timeout, timeoutCancellation.Token, () =>
                {
#if PCL
                    task.TrySetException(new TimeoutException());
#else
                    task.TrySetException(new WebException("Timeout", WebExceptionStatus.Timeout));
#endif
                    req.Abort();
                });
                req.BeginGetRequestStream(reqStrAr =>
                {
                    try
                    {
                        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);
                    }
//.........這裏部分代碼省略.........
開發者ID:kb10uy,項目名稱:CoreTweet,代碼行數:101,代碼來源:Request.Async.cs

示例3: HttpPostWithMultipartFormDataAsync


//.........這裏部分代碼省略.........
                else if(valueBuffer != null)
                    content.Add(new HttpBufferContent(valueBuffer), x.Key, 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);
#elif PCL
            var content = new MultipartFormDataContent();
            foreach (var x in prm)
            {
                var valueStream = x.Value as Stream;
                var valueBytes = x.Value as IEnumerable<byte>;

                if(valueStream != null)
                    content.Add(new StreamContent(valueStream), x.Key, "file");
                else if(valueBytes != null)
                    content.Add(new ByteArrayContent(valueBytes as byte[] ?? valueBytes.ToArray()), x.Key, "file");
                else
                    content.Add(new StringContent(x.Value.ToString()), x.Key);
            }
            req.Content = content;
            return ExecuteRequest(req, authorizationHeader, options, cancellationToken);
#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 !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
                req.UserAgent = options.UserAgent;
                req.ContentType = "multipart/form-data;boundary=" + boundary;
                req.Headers[HttpRequestHeader.Authorization] = authorizationHeader;
                options.BeforeRequestAction?.Invoke(req);

                var timeoutCancellation = new CancellationTokenSource();
                DelayAction(options.Timeout, timeoutCancellation.Token, () =>
                {
                    task.TrySetCanceled();
                    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:kyanro,項目名稱:CoreTweet,代碼行數:101,代碼來源:Request.Async.cs

示例4: 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 client = new HttpClient();
            var req = new HttpRequestMessage(HttpMethod.Get, new Uri(reqUrl));
            req.Headers.Add("Authorization", authorizationHeader);
            return ExecuteRequest(client, 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 NET45 || WP
                req.AllowReadStreamBuffering = false;
#endif
#if !(PCL || WP)                
                req.ReadWriteTimeout = options.ReadWriteTimeout;
#endif
#if !PCL
                req.UserAgent = options.UserAgent;
#endif
#if !(PCL || WP)
                req.Proxy = options.Proxy;
#endif
                req.Headers[HttpRequestHeader.Authorization] = authorizationHeader;
#if !PCL
                if(options.BeforeRequestAction != null) options.BeforeRequestAction(req);
#endif

                var timeoutCancellation = new CancellationTokenSource();
                DelayAction(options.Timeout, timeoutCancellation.Token, () =>
                {
#if PCL
                    task.TrySetException(new TimeoutException());
#else
                    task.TrySetException(new WebException("Timeout", WebExceptionStatus.Timeout));
#endif
                    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:kb10uy,項目名稱:CoreTweet,代碼行數:91,代碼來源:Request.Async.cs

示例5: HttpGetAsync

        /// <summary>
        /// Sends a GET request as an asynchronous operation.
        /// </summary>
        /// <param name="url">The URL.</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(Uri url, string authorizationHeader, ConnectionOptions options, CancellationToken cancellationToken)
        {
            if(options == null) options = new ConnectionOptions();

#if WIN_RT || PCL
            var req = new HttpRequestMessage(HttpMethod.Get, url);
            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();
                });

#if !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;
                req.UserAgent = options.UserAgent;
                options.BeforeRequestAction?.Invoke(req);

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

                ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, (_, timeout) =>
                {
                    if (!timeout) return;
                    task.TrySetCanceled();
                    req.Abort();
                }, null, options.Timeout, true);
            }
            catch(Exception ex)
            {
                task.TrySetException(ex);
            }

            return task.Task;
#endif
        }
開發者ID:kyanro,項目名稱:CoreTweet,代碼行數:76,代碼來源:Request.Async.cs


注:本文中的System.Net.Http.HttpRequestMessage.EndGetResponse方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。