locked
How to make REST requests with C# RRS feed

  • Question

  • User-1664485818 posted

    Hi folks, I'm using the following class to make a REST request 

    But I have one small problem I need to include a header i.e. Content-type: application/json

    Just not sure how to include this with the class, any help much appreciated.

    The following class was created by 

    using System;
    using System.IO;
    using System.Net;
    using System.Text;
    
    public enum HttpVerb
    {
        GET,
        POST,
        PUT,
        DELETE
    }
    
    namespace HttpUtils
    {
      public class RestClient
      {
        public string EndPoint { get; set; }
        public HttpVerb Method { get; set; }
        public string ContentType { get; set; }
        public string PostData { get; set; }
    
        public RestClient()
        {
          EndPoint = "";
          Method = HttpVerb.GET;
          ContentType = "text/xml";
          PostData = "";
        }
        public RestClient(string endpoint)
        {
          EndPoint = endpoint;
          Method = HttpVerb.GET;
          ContentType = "text/xml";
          PostData = "";
        }
        public RestClient(string endpoint, HttpVerb method)
        {
          EndPoint = endpoint;
          Method = method;
          ContentType = "text/xml";
          PostData = "";
        }
    
        public RestClient(string endpoint, HttpVerb method, string postData)
        {
          EndPoint = endpoint;
          Method = method;
          ContentType = "text/xml";
          PostData = postData;
        }
    
    
        public string MakeRequest()
        {
          return MakeRequest("");
        }
    
        public string MakeRequest(string parameters)
        {
          var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);
    
          request.Method = Method.ToString();
          request.ContentLength = 0;
          request.ContentType = ContentType;
    
          if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.POST)
          {
            var encoding = new UTF8Encoding();
            var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);
            request.ContentLength = bytes.Length;
    
            using (var writeStream = request.GetRequestStream())
            {
              writeStream.Write(bytes, 0, bytes.Length);
            }
          }
    
          using (var response = (HttpWebResponse)request.GetResponse())
          {
            var responseValue = string.Empty;
    
            if (response.StatusCode != HttpStatusCode.OK)
            {
              var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
              throw new ApplicationException(message);
            }
    
            // grab the response
            using (var responseStream = response.GetResponseStream())
            {
              if (responseStream != null)
                using (var reader = new StreamReader(responseStream))
                {
                  responseValue = reader.ReadToEnd();
                }
            }
    
            return responseValue;
          }
        }
    
      } // class
    
    }

     

    Thursday, June 30, 2016 7:45 PM

Answers

  • User2103319870 posted

    brucey

    public RestClient()

    {

             EndPoint = "";

            Method = HttpVerb.GET;

            ContentType = "text/xml";

            PostData = "";

    }

    You have multiple overrides to RestClient method, if you only want to return Json then you can change the contenttype in your overridden method to  ' application/json'

    Alternatively you can also add another override which will take contenttype also as parameter like below

    public RestClient(string endpoint, HttpVerb method,string contentType, string postData)
            {
              EndPoint = endpoint;
              Method = method;
              ContentType = contentType;
              PostData = postData;
            }

    While calling the method you can provide the output which you need ie xml or json

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 30, 2016 8:24 PM
  • User475983607 posted

    Use JSON which is a name: value format.  

    The { } means object.  

    A single name : value object is formatted as...

    {
          Reg: value
    }


     

    A multi name : value object is separated by commas.

    {
    	Reg: value,
    	Name: value
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 30, 2016 10:51 PM

All replies

  • User2103319870 posted

    brucey

    public RestClient()

    {

             EndPoint = "";

            Method = HttpVerb.GET;

            ContentType = "text/xml";

            PostData = "";

    }

    You have multiple overrides to RestClient method, if you only want to return Json then you can change the contenttype in your overridden method to  ' application/json'

    Alternatively you can also add another override which will take contenttype also as parameter like below

    public RestClient(string endpoint, HttpVerb method,string contentType, string postData)
            {
              EndPoint = endpoint;
              Method = method;
              ContentType = contentType;
              PostData = postData;
            }

    While calling the method you can provide the output which you need ie xml or json

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 30, 2016 8:24 PM
  • User-1664485818 posted

    Thanks A2H, 

    I'm feeling like a doughnut, can't believe it was staring me in the face!!

    Another silly question here, how do you pass more than one parameter, code below;

    var client = new RestClient();
    client.EndPoint = @"http:\\myRestService.com\api\"; ;
    client.Method = HttpVerb.POST;
    client.PostData = "{Reg: value}";
    var json = client.MakeRequest();

    Thursday, June 30, 2016 10:01 PM
  • User475983607 posted

    Use JSON which is a name: value format.  

    The { } means object.  

    A single name : value object is formatted as...

    {
          Reg: value
    }


     

    A multi name : value object is separated by commas.

    {
    	Reg: value,
    	Name: value
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 30, 2016 10:51 PM
  • User36583972 posted

    Hi brucey,

    Another silly question here, how do you pass more than one parameter, code below;

    From your description, you can refer the following code/link.

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.check-mot.service.gov.uk/");
    
                request.Method = "POST";
                request.KeepAlive = true;
                //request.ContentLength = data.Length;
                //request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
                //request.UseDefaultCredentials = true;
                //request.Credentials = new NetworkCredential("username", "password", "domain");
                request.ContentType = "application/json; charset=utf-8";
                //request.ContentType = "application/x-www-form-urlencoded";
    
                // write the data to the request stream         
                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {
                    string PostData = new JavaScriptSerializer().Serialize(new
                    {
                        PostDataid = "testID",
                        PostDatasword = "test Data"
                    });
                    writer.Write(PostData);
    
                    //string data = "Registration number=136260&Vehicle make=make name";
                    //writer.Write(data);
                }
    
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string myResponse = "";
                using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))
                {
                    myResponse = sr.ReadToEnd();
                }
    
    
    

    HttpWebRequest post JSON to the server:

    http://stackoverflow.com/questions/9145667/how-to-post-json-to-the-server

    Best Regards,

    Yohann Lu

    Friday, July 1, 2016 2:03 AM
  • User-1664485818 posted

    How do I pass the value within the variable to the string!!

    i.e. how do I pass the value within string make to the Client.Post: make

                string make = "Toyota";
                string registration = "WR08SZE"; 
    
    
                var client = new RestClient();
                client.EndPoint = @"https://www.check-mot.service.gov.uk/api/v1/mot-history\"; ;
                client.Method = HttpVerb.POST;
                client.PostData = "{PostReg: registration, PostMake: make}";
                var json = client.MakeRequest();

    Friday, July 1, 2016 1:53 PM
  • User475983607 posted

    PostData is a string so you need to build a JSON formatted string.

    string json = @"{PostReg: '" + registration + "', " + "PostMake: '" + make + "'}";
    client.PostData = json";



    Friday, July 1, 2016 2:33 PM