Profile

Click to view full profile
Hi, I'm Veerapat Sriarunrungrueang, an expert in technology field, especially full stack web development and performance testing.This is my coding diary. I usually develop and keep code snippets or some tricks, and update to this diary when I have time. Nowadays, I've been giving counsel to many well-known firms in Thailand.
view more...

Monday, November 26, 2012

HTTP POST data via WebClient and WebRequest

To request HTTP with POST method in .NET, there are 2 classes applicable to do that: WebClient, and WebRequest. I will describe  both ways in post. Normally to send the data back via POST method, there are 2 kinds of content-type (that I know) are url-encode, multipart. These two content types have an effect for the specific format for a receiver and how to construct a form message. In this post I will explain only url-encode. Firstly, we should know how to construct a format. For urlencode format, the format is very similar to querystring format like "{key1}={value1}&{key2}={value2}...". Moreover, we should encode the values like a GET parameter string (not necessary but for some characters, they need to).

To specific content-type for urlencode is set its value to "application/x-www-form-urlencoded".

Example 1: using WebClient
using System.Web;
...
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
     // Show a return message when upload is completed
     var result = (string)e.Result;
     MessageBox.Show(result);
}

private void Do_Something()
{
      string name = "Hello";
      string url = "<host ip>";
      var base64 = "name=" + HttpUtility.UrlEncode(result);

      var wc = new WebClient();
      wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
      wc.UploadStringCompleted += wc_UploadStringCompleted;
      wc.UploadStringAsync(new Uri(url), "POST", base64);
}
Example 2: using WebRequest
using System.Net;
...
private void Do_Something()
{
      string name = "Hello";
      string url = "<host ip>";
      var base64 = "name=" + HttpUtility.UrlEncode(result);

      var encode = Encoding.UTF8.GetBytes(base64);

      var request = WebRequest.Create(new Uri(url));
      request.Method = "POST";
      request.ContentType = "application/x-www-form-urlencoded";
      request.ContentLength = encode.Length;
      Stream dataStream = request.GetRequestStream();
      dataStream.Write(encode, 0, encode.Length);
      dataStream.Close();

      using (var response = request.GetResponse())
      {
           using (var reader = new StreamReader(response.GetResponseStream()))
           {
                // Show a response message
                string responseText = reader.ReadToEnd();
                MessageBox.Show(responseText );
            }
      }
}
The different from these 2 methods in my opinion are details for handling data i.e. We need to create delegate function for handling task when uploading is done, but WebRequest doesn't need to. Moreoever, WebClient has higher level of data sending compared to WebRequest. WebRequest need to pack data into byte array, but WebClient can send them as a pack of string directly.

No comments:

Post a Comment