Calling REST APi from server side code - C#

Hi,

I was working on a project where i got a web api url with parameters, i was asked to consume this api and get response from there.

I got below details:

  • Api url
  • parameters
  • and response code eg 200 for ok, 404 for not found etc.

Here is the code which will consume the web api and will get response from there.
This is 100% working code.

public class Program
    {
       
        static void Main(string[] args)
        {
            Program.CreateObject();
        }

        private static void CreateObject()
        {
           
            string name = "jack";
            string phone= "0000000000";
          

            string URL = "http://myserver/api.php?name=" + name + "&phone=" + phone;
            string DATA = @"{""name"":""jack""},{""phone"":""0000000000""};

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = DATA.Length;
            StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
            requestWriter.Write(DATA);
            requestWriter.Close();

            try
            {
                WebResponse webResponse = request.GetResponse();
                Stream webStream = webResponse.GetResponseStream();
                StreamReader responseReader = new StreamReader(webStream);
                string response = responseReader.ReadToEnd();
                Console.Out.WriteLine(response); //Get Web response and proceed accordingly
                responseReader.Close();
            }
            catch (Exception e)
            {
                Console.Out.WriteLine("-----------------");
                Console.Out.WriteLine(e.Message);
            }

        }
    }

Popular posts from this blog

All about SharePoint 2010 Content Type Hub

Calling ASP.Net WebMethod using jQuery AJAX