Tuesday, September 17, 2013

HTTP GET and POST with C#

GET and POST are two different methods to send data to a HTTP server. In this post I briefly want to explain the differences between them and how to implement them in C#.
For GET the data is just appended to the URL, e.g. example.com/?field=id. A direct consequence is, that the length of these data is limited by the maximal URL length.
For POST a data block is transfered without the use of the URL.
Advantages of GET are now for example the clearness (which could also be interpreted as unsecureness though) and the little overhead, of POST the unlimited transfer size as well as that file upload is only doable with POST.

Both methods we can now use e.g. with a System.Net.WebRequest. For the following sample codes System.Net and System.IO have to be included.
In POST and GET we first create the request, note that here for GET the URL needs to contain already all data.

WebRequest MyRequest;
MyRequest = WebRequest.Create(URL);
MyRequest.Method = "POST"; // "GET" for GET
In the case of POST the request now has to be submitted, which can be done as follows:

Stream DataStream = MyRequest.GetRequestStream();
Byte[] Data = Encoding.UTF8.GetBytes("exampledata");
DataStream.Write(Data, 0, Data.Length);
In both cases a possible answer of the server can be read-out:

            Stream ResponseStream;
            ResponseStream = MyRequest.GetResponse().GetResponseStream();
            StreamReader ResponseReader = new StreamReader(ResponseStream);

            string TempLine = "";
            int i = 0;
            string Result = "";
            while (TempLine != null)
                TempLine = ResponseReader.ReadLine();
                if (TempLine != null)
                    Result += TempLine;

No comments:

Post a Comment