How can I Post data using HttpWebRequest?

我的梦境 提交于 2021-01-27 14:02:59

问题


I have this HttpWebRequest:

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

But I need to add a payload to the body of the request like this:

Jlpt = 2

Can someone help and tell me how I can add data to the POST ?


回答1:


You can do by this

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();

but I suggest you use HttpClient rather than HttpWebRequest in this case




回答2:


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;
}

where data is any object you want to send



来源:https://stackoverflow.com/questions/39246236/how-can-i-post-data-using-httpwebrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!