How to call a rest api from C#

Here in this article I am trying to give an easy approach to call a rest/web api from our C# code.It is quite simple and there are many approaches  to do the same.Here I am giving the example with webrequest and webresponse for the get method.It’s the HTTP-specific implementation of WebRequest class which was originally used to deal with HTTP requests, but it was made obsolete and replaced by the WebClient class

HttpWebRequest class does not block the user interface.

HttpWebResponse class provides a container for the incoming responses.

string URL=""
string urlParameters = "?Id=123" ;
System.Net.HttpWebRequest webrequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(URL + urlParameters);
webrequest.Method = "GET";
webrequest.ContentType = "application/json";

System.Net.HttpWebResponse webresponse = (System.Net.HttpWebResponse)webrequest.GetResponse();
System.Text.Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
StreamReader responseStream = new StreamReader(webresponse.GetResponseStream(), enc);
string result = string.Empty;
result = responseStream.ReadToEnd();
Posted in

Leave a Reply

Your email address will not be published. Required fields are marked *