16

I'm in the process of creating a C# console application which reads text from a text file, turns it into a JSON formatted string (held in a string variable), and needs to POST the JSON request to a web api. I'm using .NET Framework 4.

My struggle is with creating the request and getting the response, using C#. What is the basic code that is necessary? Comments in the code would be helpful. What I've got so far is the below, but I'm not sure if I'm on the right track.

//POST JSON REQUEST TO API
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("POST URL GOES HERE?");

request.Method = "POST";
request.ContentType = "application/json";

System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(jsonPOSTString);

request.ContentLength = bytes.Length;

using (Stream requestStream = request.GetRequestStream())
{
    // Send the data.
    requestStream.Write(bytes, 0, bytes.Length);
}

//RESPONSE HERE
3
  • 1
    Yes, you are on the right track.
    – L.B
    Feb 12, 2014 at 15:26
  • Does it work? Then what is the question?
    – CodeCaster
    Feb 12, 2014 at 15:29
  • I was basically asking if the code I had posted was a correct was to do a POST, and wegrata posted a simpler solution which worked for me.
    – kyle_13
    Feb 13, 2014 at 14:07

2 Answers 2

51

Have you tried using the WebClient class?

you should be able to use

string result = "";
using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "application/json"; 
    result = client.UploadString(url, "POST", json);
}
Console.WriteLine(result);

Documentation at

http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.110%29.aspx

http://msdn.microsoft.com/en-us/library/d0d3595k%28v=vs.110%29.aspx

9
  • I did wonder on the benefits of the WebClient. I think the difference is clearly shown on this page, just pure simplicity
    – Paul C
    Feb 12, 2014 at 15:30
  • That is simple...so is the code inside the using statement basically posting the json string to the url, and at then getting the response and assigning it to the result string, which you then are outputting with the Console.Writeline?
    – kyle_13
    Feb 12, 2014 at 15:53
  • Yep the code inside the using posts the data, it also has UploadData and UploadFile methods that function in a similar way to UploadString. and the response is returned and placed into result and then dumped to console
    – wegrata
    Feb 12, 2014 at 16:07
  • 2
    This didn't work for me until I added this code before the call client.Headers[HttpRequestHeader.ContentType] = "application/json";
    – TheJonz
    Jan 9, 2015 at 19:21
  • 1
    I think you also need client.Encoding = Encoding.UTF8
    – Joe
    Jun 22, 2016 at 12:01
2

Try using Web API HttpClient

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://domain.com/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            // HTTP POST
            var obj = new MyObject() { Str = "MyString"};
            response = await client.PostAsJsonAsync("POST URL GOES HERE?", obj );
            if (response.IsSuccessStatusCode)
            {
                response.//.. Contains the returned content.
            }
        }
    }

You can find more details here Web API Clients

1
  • MediaTypeWithQualityHeaderValue fails and PostAsJsonAsync fails... "are you missing an assembly or reference"? This code should've been explained and proper assemblies cited. Just posting a link that didn't even link directly to where this code was found doesn't help. A full example should have been provided and explained, as links can often become broken.
    – vapcguy
    Apr 17, 2020 at 0:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.