Monday, February 18, 2013

Implementing POST requests in .NET

Data transfer between the client and server takes place over the sockets and in byte format. Which means that anything a client needs to send to a server must be converted into bytes either implicitly or explicitly.
POST requests differ from other HTTP requests (apart from PUT) in the concept that in POST request, the client sends data in the 'body' of the HTTP packet. Hence we should understand how to send this data on the client side and at the same time how do we extract the body from the HTTP packet on the server side for further processing. Most of the sites only speak about the GET requests which are far simpler to consume by any client. It is the POST/PUT requests which needs to be understood very well.

As mentioned earlier, the data needs to be sent as a stream of bytes hence if you need to transfer an object of a class then it must be serialized into a stream of bytes by serialization. This post relates with JSON (de)serialization.

Lets take a look at some client and server side code in .NET.

Client Side:


string endPoint = "http://localhost:20909/surveyupload"; // endpoint address to send the data on
var request = (HttpWebRequest)WebRequest.Create(endPoint);
request.Method = "POST";          

string PostData = Newtonsoft.Json.JsonConvert.SerializeObject(survey); // JSON serialization

if (!string.IsNullOrEmpty(PostData))
{                  
         byte[] byteContent = Encoding.UTF8.GetBytes(PostData);                

         using (var writeStream = request.GetRequestStream())
         {
                writeStream.Write(byteContent, 0, byteContent.Length);
          }
  }



using (var response = (HttpWebResponse)request.GetResponse())
{
      var responseValue = string.Empty;

      if (response.StatusCode != HttpStatusCode.OK)
      {
              var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
                        throw new ApplicationException(message);
       }

       // grab the response
       using (var responseStream = response.GetResponseStream())
       {
             if (responseStream != null)
             using (var reader = new StreamReader(responseStream))
             {
                   responseValue = reader.ReadToEnd();
               }
         }
}


Server side:
The following method is your sample function implemented on the server side, that maps to the endpoint request made from client.


public string GetFile(System.IO.Stream data)
        {
            string JSONInString = string.Empty;
            using (StreamReader reader = new StreamReader(data))
            {
                JSONInString = reader.ReadToEnd();
                reader.Close();            
            }
            // Deserialize the streamed byte data into the object of known type as below
            SurveyData ReceivedData = JsonConvert.DeserializeObject<SurveyData>(JSONInString);
            if (ReceivedData != null)
                return "Success";
            else
                return "Failed";
        }

That's it. It is very easy to implement the POST requests in .NET. The above client requests can be further elaborated depending upon the requirement. This may involve adding additional headers, modifying content-types, user-agent, etc. properties of the Http request.

For details regarding the importance of REST services, please refer to, http://intelligentfactory.blogspot.co.uk/2012/09/rest-services-primer-all-about-rest.html