如何使用WebRequest发布?

时间:2010-04-11 14:59:07

标签: c#

使用WebRequest如何发布内容,我应该使用GetRequestStream吗?以及如何格式化POST字符串

由于

2 个答案:

答案 0 :(得分:12)

var request = WebRequest.Create("http://www.example.com");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (var writer = new StreamWriter(request.GetRequestStream()))
{
    // write to the body of the POST request
    writer.Write("param1=value1&param2=value2");
}

答案 1 :(得分:7)

作为HttpWebRequest的替代方案,请查看WebClient.UploadValues

var values = new NameValueCollection();
values.Add("param1", "value1");
values.Add("param2", "value2");

new WebClient().UploadValues("http://www.example.com", values);