4

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 ?

Mostafiz
  • 7,243
  • 3
  • 28
  • 42
Alan2
  • 23,493
  • 79
  • 256
  • 450
  • If you can, use `HttpClient` rather than `HttpWebRequest`. It has a more modern, asynchronous API, and a much more straightforward way to add a payload to a request. – Thomas Levesque Aug 31 '16 at 09:53

2 Answers2

9

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

Mostafiz
  • 7,243
  • 3
  • 28
  • 42
  • Thanks very much. Can you explain why you suggest to use HttpClient? What's the difference? Thank you. – Alan2 Aug 31 '16 at 09:58
  • you can find more detail in this SO thread http://stackoverflow.com/questions/22214930/httpclient-vs-httpwebrequest – Mostafiz Aug 31 '16 at 09:59
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

Guru Stron
  • 102,774
  • 10
  • 95
  • 132