Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create JSON post to api using C# [closed]

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
like image 778
kyle_13 Avatar asked Feb 12 '14 15:02

kyle_13


People also ask

How do I post JSON data to API using C #?

To post JSON to a REST API endpoint using C#/. NET, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the C#/. NET POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.

How do I make a HTTP POST Web request?

WebRequest wRequest = WebRequest. Create("http://www.example.com/about.aspx"); Specify a protocol method that permits data to be sent with a request, such as the HTTP POST method: wRequest.


1 Answers

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

like image 119
wegrata Avatar answered Oct 03 '22 18:10

wegrata