Categories
C#

C# Post JSON to HTTP

Basically, in this example we are going to post a Name,Surname,Phone and Email data in JSON form. Then we will get our data as response and deserialize to object from JSON. Finally we will print name value which we send first.

Firstly, we need to install Newtonsoft.Json package using nuget. Follow instructions on https://www.newtonsoft.com/json In this example i am going to use Person Class to serialize our object.

#Person.cs    
public class Person
    {
        public Person()
        {
        }
        public string name { get; set; }
        public string surname { get; set; }
        public string phone { get; set; }
        public string email { get; set;}     
    }

We are sending our JSON to http page then we are getting response and printing name value in it.

  System.Net.WebRequest request = System.Net.WebRequest.Create("http://YOUR_URL/your_page.php");
            request.Method = "POST";
            Person person = new Person();
            person.name = "John";
            person.surname = "Doe";
            person.phone = "+1234567";
            person.email = "[email protected]";
            String myjson = "data=" +
 //Serializing object
 Newtonsoft.Json.JsonConvert.SerializeObject(person);

            byte[] byteArray = Encoding.UTF8.GetBytes(myjson);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            System.IO.Stream dataStream = request.GetRequestStream();          
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            System.Net.WebResponse response = request.GetResponse(); 
            Console.WriteLine(((System.Net.HttpWebResponse)response).StatusDescription);

            using (dataStream = response.GetResponseStream())
            { 
                System.IO.StreamReader reader = new System.IO.StreamReader(dataStream);
                string responseFromServer = reader.ReadToEnd();
//Deserializing Response
                Person p = Newtonsoft.Json.JsonConvert.DeserializeObject< Person>(responseFromServer);
                Console.WriteLine(p.name);
            }

            response.Close();

Just a page to receive our data and serve it back as response.

//your_page.php

<?php

echo $_POST['data'];