Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I Post data using HttpWebRequest?

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 ?

like image 512
Alan2 Avatar asked Oct 19 '25 20:10

Alan2


2 Answers

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

like image 146
Mostafiz Avatar answered Oct 21 '25 08:10

Mostafiz


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

like image 27
Guru Stron Avatar answered Oct 21 '25 08:10

Guru Stron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!