The HTTP (Hypertext Transfer Protocol) is designed to enable communications between clients and servers. It works as a request-response protocol between a client and server. The two most common HTTP methods are:
  1. GET
  2. POST

How to send data by using the WebRequest class C# .Net
HTTP POST is one of the most common HTTP methods. It is used to send data to a web-server to create or update a resource and is stored in the request body of the HTTP request:

POST /test/about.html HTTP/1.1
Host: net-informations.com
name1=value1&name2=value2
In C# WebRequest Class is to makes a request to a URI (Uniform Resource Identifier). Requests are sent from an application to a particular Uniform Resource Identifier, such as a Web page on a server. WebRequest.Create Method used to initialize new WebRequest instances. The actual behaviour of WebRequest instances at run time is determined by the descendant class returned by the WebRequest.Create method.

WebRequest wRequest = WebRequest.Create("http://www.example.com/about.aspx");
Specify a protocol method that permits data to be sent with a request, such as the HTTP POST method:

wRequest.Method = "POST";
Get the stream that holds request data by calling the GetRequestStream method.

Stream webData = wRequest.GetRequestStream();
Write the data to the Stream object returned by the GetRequestStream method.

webData.Write(bArray, 0, bArray.Length);
To get the stream containing response data sent by the server, call the WebResponse.GetResponseStream method of your WebResponse object.

webData = webResponse.GetResponseStream();

Create HTTP POST with WebRequest class C#
The following C# example shows how to send data to a server and read the data in its response:

using System;
using System.IO;
using System.Net;
using System.Text;
namespace PostRequest
{
  class Program
  {
    static void Main(string[] args)
    {
      WebRequest wRequest = WebRequest.Create("http://www.example.com/about.aspx");
      wRequest.Method = "POST";
      string postString = "This message send to webserver";
      byte[] bArray = Encoding.UTF8.GetBytes(postString);
      wRequest.ContentType = "application/x-www-form-urlencoded";
      wRequest.ContentLength = bArray.Length;
      Stream webData = wRequest.GetRequestStream();
      webData.Write(bArray, 0, bArray.Length);
      webData.Close();
      WebResponse webResponse = wRequest.GetResponse();
      Console.WriteLine(((HttpWebResponse)webResponse).StatusDescription);
      webData = webResponse.GetResponseStream();
      StreamReader reader = new StreamReader(webData);
      string responseFromServer = reader.ReadToEnd();
      Console.WriteLine(responseFromServer);
      reader.Close();
      webData.Close();
      webResponse.Close();
      Console.ReadKey();
    }
  }
}
Prev
Index Page
Next
©Net-informations.com