Saturday, January 24, 2015

Web API :Utility To read Json output From WebResponse


Introduction

The below utility fetches the output from API request through HTTP in JSON format.


public static class JsonRequestStreamUtility
    {
        public static WebRequest CreateRequest(string url, string method = WebRequestMethods.Http.Get, string body = null)
        {
            var webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = method;
            webRequest.Accept = "application/json";
            webRequest.Headers.Add("Accept-Charset", "utf-8");
            webRequest.ContentType = "application/json";

            webRequest.Proxy = new System.Net.WebProxy()
                {
                    Address = new Uri("xyz"),
                    UseDefaultCredentials = true,
                };
            
            if (body == null)
                return webRequest;

            using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
            {
                streamWriter.Write(body);
            }
            return webRequest;
        }

        public static string ExecuteJsonResponseStream(WebRequest webRequest)
        {
            
            if (webRequest == null) throw new ArgumentNullException("webRequest");

              try
            {

                // Get the stream associated with the response.
                Stream receiveStream = webRequest.GetResponse().GetResponseStream();

                // Pipes the stream to a higher level stream reader with the required encoding format. 
                StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
                return  readStream.ReadToEnd();
                
            }
            catch (WebException we)
            {
                              
                return string.empty;
            }
        }
    }

No comments :