0

我使用以下代码在 C# 中执行异步 HTTP 请求。

    private static Task GetUrl(string url)
    {
        var request = (HttpWebRequest)WebRequest.Create(url);
        request.UserAgent =
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.69 Safari/537.36";
        request.Accept = "text/html";
        return Task
            .Factory
            .FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, url)
            .ContinueWith(t =>
            {
                if (t.IsCompleted)
                {
                    using (var stream = t.Result.GetResponseStream())
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            //Console.WriteLine("-- Successfully downloaded {0} --", t.AsyncState);
                            //Console.WriteLine(reader.ReadToEnd());
                        }
                    }
                }
                else if (t.IsFaulted)
                {
                    Console.WriteLine("There was an error downloading {0} - {1}", t.AsyncState, t.Exception);
                }
            });
    }

但是我不确定我应该如何修改上面的代码以支持 HTTP 发布。任何帮助表示赞赏!

特别是我想知道我应该如何将 BeginGetRequestStream 和 EndGetRequestStream 添加到当前函数中......

4

1 回答 1

1

使用 HttpWebRequest 的 Method 属性:

request.Method = "POST";
于 2013-10-11T13:41:37.827 回答