Tuesday, January 6, 2015

Consume JSON web service by posting JSON to the server as input

Following code describes how we can consume a JSON web service by passing inputs as in JSON formats.

public static void GetJson()
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("<>");
            httpWebRequest.ContentType = "application/json";

            httpWebRequest.Method = "POST";
            httpWebRequest.Accept = "application/json";
            IWebProxy proxy = httpWebRequest.Proxy;
            if (proxy != null)
                string proxyuri = proxy.GetProxy(httpWebRequest.RequestUri).ToString();
                httpWebRequest.UseDefaultCredentials = true;
                httpWebRequest.Proxy = new WebProxy(proxyuri, false);
                httpWebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
  //Sample JSON input
                string json = "{\"filter\":\"CREATED_DATE\",\"customerList\": [5478, 25414],\"fromDate\":\"2014-08-13\",\"toDate\":\"2014-09-11\",\"status\":\"transit\"}";


                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                    var result = streamReader.ReadToEnd();

The Sample JSON input added at the above code is passed to the server and the result is queried based in the provided input.

No comments:

Post a Comment