C# 4.0 中的异步 HTTP POST
本文关键字:异步 HTTP POST | 更新日期: 2023-09-27 18:35:09
我使用以下代码在 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 添加到当前函数中......
使用 HttpWebRequest 的 Method 属性:
request.Method = "POST";