[英]Asynchronous HTTP POST in C# 4.0
I've used the following code to perform asynchronous HTTP request in C#. 我使用以下代码在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);
}
});
}
However I'm not sure how I should modify the above code to support HTTP post as well. 但是我不确定如何修改上述代码以也支持HTTP发布。 Any help is appreciated!
任何帮助表示赞赏!
In particular I'd like to know how I should add BeginGetRequestStream and EndGetRequestStream into the current function... 特别是我想知道如何将BeginGetRequestStream和EndGetRequestStream添加到当前函数中...
使用HttpWebRequest的Method属性:
request.Method = "POST";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.