如何使用HttpWebRequest发布数据?

时间:2016-08-31 09:49:00

标签: c# xamarin httpwebrequest httprequest

我有HttpWebRequest

var request = HttpWebRequest.Create("http://example.com/api/Phrase/GetJDTO");
request.ContentType = "application/json";
request.Method = "POST";

但我需要在请求正文中添加一个有效负载,如下所示:

Jlpt = 2

有人可以帮忙告诉我如何将数据添加到POST中吗?

2 个答案:

答案 0 :(得分:6)

你可以这样做

var request = HttpWebRequest.Create("http://example.com/api/Phrase/GetJDTO");

var postData = "Jlpt = 2";
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

var response = (HttpWebResponse)request.GetResponse();

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

但我建议您在这种情况下使用HttpClient而不是HttpWebRequest

答案 1 :(得分:1)

if (data != null)
{
    request.ContentType = "application/json";
    using (var stream = new StreamWriter(request.GetRequestStream()))
    {
        var serialized = JsonConvert.SerializeObject(data);
        stream.Write(serialized);
    }
}
else
{
    request.ContentLength = 0;
}

其中data是您要发送的任何对象