Best way to call a JSON WebService from a .NET Console Best way to call a JSON WebService from a .NET Console json json

Best way to call a JSON WebService from a .NET Console


I use HttpWebRequest to GET from the web service, which returns me a JSON string. It looks something like this for a GET:

// Returns JSON stringstring GET(string url) {    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);    try {        WebResponse response = request.GetResponse();        using (Stream responseStream = response.GetResponseStream()) {            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);            return reader.ReadToEnd();        }    }    catch (WebException ex) {        WebResponse errorResponse = ex.Response;        using (Stream responseStream = errorResponse.GetResponseStream())        {            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));            String errorText = reader.ReadToEnd();            // log errorText        }        throw;    }}

I then use JSON.Net to dynamically parse the string.Alternatively, you can generate the C# class statically from sample JSON output using this codeplex tool: http://jsonclassgenerator.codeplex.com/

POST looks like this:

// POST a JSON stringvoid POST(string url, string jsonContent) {    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);    request.Method = "POST";    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();    Byte[] byteArray = encoding.GetBytes(jsonContent);    request.ContentLength = byteArray.Length;    request.ContentType = @"application/json";    using (Stream dataStream = request.GetRequestStream()) {        dataStream.Write(byteArray, 0, byteArray.Length);    }    long length = 0;    try {        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {            length = response.ContentLength;        }    }    catch (WebException ex) {        // Log exception and throw as for GET example above    }}

I use code like this in automated tests of our web service.


WebClient to fetch the contents from the remote url and JavaScriptSerializer or Json.NET to deserialize the JSON into a .NET object. For example you define a model class which will reflect the JSON structure and then:

using (var client = new WebClient()){    var json = client.DownloadString("http://example.com/json");    var serializer = new JavaScriptSerializer();    SomeModel model = serializer.Deserialize<SomeModel>(json);    // TODO: do something with the model}

There are also some REST client frameworks you may checkout such as RestSharp.


Although the existing answers are valid approaches , they are antiquated . HttpClient is a modern interface for working with RESTful web services . Check the examples section of the page in the link , it has a very straightforward use case for an asynchronous HTTP GET .

using (var client = new System.Net.Http.HttpClient()){    return await client.GetStringAsync("https://reqres.in/api/users/3"); //uri}