如何使用HttpWebRequest发布数据

本文关键字:数据 布数据 何使用 HttpWebRequest | 更新日期: 2023-09-27 18:05:08

我有这个HttpWebRequest:

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

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

Jlpt = 2

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

如何使用HttpWebRequest发布数据

你可以通过这个

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

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是要发送的任何对象