Alan Alan - 1 year ago 73
C# Question

How can I Post data using HttpWebRequest?

I have this


var request = HttpWebRequest.Create("");
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 ?

Answer Source

You can do by this

var request = HttpWebRequest.Create("");

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