Solved

Sending a JSON request in C# using an HTTP POST

Posted on 2015-01-19
5
660 Views
Last Modified: 2015-01-26
Hi all!  I need pointed in the right direction with something.  In C# on .Net 4.5, I need to send JSON to a REST API via an HTTP POST (running Windows on .Net 4.5 also).  The JSON details a single entity; the structure never changes.

Example:
{
  "A": "string",
  "B": " string ",
  "C": {
          "1": " string ",
          "2": " string ",
          "3": " string ",
          "4": {
                 "a":" string ",
                  "b":" string ",
                  "c":" string "
                    }
            }
}

The REST API responds back to the client with JSON.  This is part of a server deployment the client is running from, which is a one time action for the life of that server.  So client performance is not an issue.  I will have to build in other logic to allow for a retry if the REST API doesn’t return the object in a timely fashion.  Let’s say it will retry every 60 seconds for a few minutes before eventually timing out.

I’m looking for two things.  
1) What class should I use to make the connection to the REST API.  
2) Should I bother with anything other than a regular expression if the JSON strings I send over will always be formatted the same?

Thoughts on going about this, and do you have a sample or some webpages you can point me to?  I want to avoid using non-Microsoft shipped code if possible.  Using the HttpClient seems like a really good option; http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client.  But then there is WebRequest..  http://msdn.microsoft.com/en-us/library/debx8sh9(v=vs.110).aspx.  

I’m a fairly novice programmer outside of some medium level scripting.  I’m not looking for anything too fancy.  
0
Comment
Question by:1974Widget
  • 2
  • 2
5 Comments
 
LVL 74

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 333 total points
Comment Utility
What class should I use to make the connection to the REST API.
Either of the two classes you mention should do the job. There is also the WebClient class available. It's a bit easier to use than HttpClient, but you lose some of the granularity and control for the sake of the ease.

Should I bother with anything other than a regular expression if the JSON strings I send over will always be formatted the same?
I don't see what regular expressions have to do with this task. Myself, I would create a class structure to mimic the JSON structure, and then rely on serialization to transform a class instance in memory into JSON over the wire. However, it's unclear as to whether or not you need that. Can you clarify:  is it the structure only that is constant, or is the data itself constant as well?
0
 

Author Comment

by:1974Widget
Comment Utility
The structure is constant.  The data itself won't be.
0
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 333 total points
Comment Utility
You're limiting yourself a tad by saying, "I want to avoid using non-Microsoft shipped code if possible." Nevertheless, one approach is to create a series of classes as I mentioned. Then you can use the DataContractJsonSerializer to serialize these classes into the appropriate JSON. You'll have to decorate your classes with some attributes in order to get the serialization to work, but it isn't too complicated:

using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;

namespace _28599653
{
    class Program
    {
        static void Main(string[] args)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Root));
            Root instance = new Root() { A = "string", B = "string", C = new Child() { One = "string", Two = "string", Three = "string", Four = new ChildChild() { a = "string", b = "string", c = "string" } } };
            MemoryStream ms = new MemoryStream();
            string json;

            serializer.WriteObject(ms, instance);
            ms.Position = 0;
            json = Encoding.UTF8.GetString(ms.ToArray());
            System.Diagnostics.Debugger.Break();
        }

        [DataContract]
        public class Root
        {
            [DataMember]
            public string A { get; set; }
            [DataMember]
            public string B { get; set; }
            [DataMember]
            public Child C { get; set; }
        }

        [DataContract]
        public class Child
        {
            [DataMember(Name = "1")]
            public string One { get; set; }
            [DataMember(Name = "2")]
            public string Two { get; set; }
            [DataMember(Name = "3")]
            public string Three { get; set; }
            [DataMember(Name = "4")]
            public ChildChild Four { get; set; }
        }

        [DataContract]
        public class ChildChild
        {
            [DataMember]
            public string a { get; set; }
            [DataMember]
            public string b { get; set; }
            [DataMember]
            public string c { get; set; }
        }
    }
}

Open in new window


In the above, you can see that I create a "Root" class which the overarching structure for the entire object. The name is really inconsequential; I used "Root" just as an example. From there, you trace down the JSON hierarchy to add to this object properties which correspond to those found in the JSON. Each time in the JSON that you get to a property which is not a simple type (e.g. string, int, date), you introduce a new class. That is what I'm doing with "Child" and "ChildChild". Again, the names are only for example, and you can either change them directly, or use the DataContract's Name property to override what the serializer would normally output.
0
 
LVL 15

Assisted Solution

by:navneethegde
navneethegde earned 167 total points
Comment Utility
Try this way to Get and Post Json data to API and get JSON result.
from : http://openweathermap.org/

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Web.Script.Serialization;

namespace ConsoleApplication7
{
    class Program
    {
        static void Main(string[] args)
        {
            var relativeUri = "data/2.5/weather?q=London,uk";

            //get
            var sendGetResult = GetSendRequest(relativeUri);

            //post
            var Requestor = new Employee { Id = 1, Name = "Navneet" };

            string jsonRequester = new JavaScriptSerializer().Serialize(Requestor);
            var sendPostResult = PostSendRequest(relativeUri, jsonRequester);

        }

        private class Employee
        {
            public Employee() { }

            public int Id { get; set; }
            public string Name { get; set; }

        }

        static Dictionary<string, dynamic> GetSendRequest(string relativeUri)
        {
            var ServiceUri = "http://api.openweathermap.org/";
            var response = new Dictionary<string, dynamic>();
            try
            {
                var client = new HttpClient { BaseAddress = new Uri(ServiceUri) };
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage responseMessage = null;
                responseMessage = client.GetAsync(relativeUri).Result;

                HttpStatusCode statusCode;
                Enum.TryParse(responseMessage.StatusCode.ToString(), out statusCode);

                var result = responseMessage.Content.ReadAsStringAsync().Result;

                if (statusCode != HttpStatusCode.OK)
                {
                    //send error response
                }

                response = new JavaScriptSerializer().Deserialize<Dictionary<string, dynamic>>(result);
                return response;
            }
            catch (Exception)
            {
                throw;
            }
        }


        static Dictionary<string, dynamic> PostSendRequest(string relativeUri, object postData)
        {
            var ServiceUri = "http://api.openweathermap.org/";
            var response = new Dictionary<string, dynamic>();
            try
            {
                var client = new HttpClient { BaseAddress = new Uri(ServiceUri) };
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage responseMessage = null;
                responseMessage = client.PostAsJsonAsync(relativeUri, postData).Result;

                HttpStatusCode statusCode;
                Enum.TryParse(responseMessage.StatusCode.ToString(), out statusCode);

                var result = responseMessage.Content.ReadAsStringAsync().Result;

                if (statusCode != HttpStatusCode.OK)
                {
                    //send error response
                }

                response = new JavaScriptSerializer().Deserialize<Dictionary<string, dynamic>>(result);
                return response;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}

Open in new window


Thanks!
Navneet
0
 

Author Closing Comment

by:1974Widget
Comment Utility
Thanks all!  I haven't tried these yet, but this get's me started down the proper path.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
In order to have all security and back ups taken care of, WordPress users can sign up for services with WP Engine.
The purpose of this video is to demonstrate how to set up the WordPress backend so that each page automatically generates a Mailchimp signup form in the sidebar. This will be demonstrated using a Windows 8 PC. Tools Used are Photoshop, Awesome…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now