Search code examples
c#asp.net.netrestwcf-rest

How to consume a web services end point through c#


I want to make a get request to the following end point through C#.

http://api.example.com/1/companies/{id}

I was looking at WCF rest starter kit and wonder there are other ways to make get requests easily than installing rest starter kit.

Please suggest. Thanks,


Solution

  • Here's a method that will execute GET from URL and return string:

    public static string GetResponse(string endPoint)
            {
                HttpWebRequest request = CreateWebRequest(endPoint);
    
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    var responseValue = string.Empty;
    
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        string message = String.Format("POST failed. Received HTTP {0}", response.StatusCode);
                        throw new ApplicationException(message);
                    }
    
                    // grab the response  
                    using (var responseStream = response.GetResponseStream())
                    {
                        using (var reader = new StreamReader(responseStream))
                        {
                            responseValue = reader.ReadToEnd();
                        }
                    }
    
                    return responseValue;
                }
            }
    

    EDIT:

    private static HttpWebRequest CreateWebRequest(string endPoint)
            {
                var request = (HttpWebRequest)WebRequest.Create(endPoint);
    
                request.Method = "GET";
                request.ContentLength = 0;
                request.ContentType = "text/json";
    
                return request;
            }