Sunday, March 8, 2015

Send HTTP POST Parameters

In a previous post I already explained the basic usage of HTTP POST and GET. These are methods for transfering data over the HTTP protocol, for example to webservers. In C# there are multiple methods to do this, in the previous post for example a WebRequest was used, but also the usage of a WebClient control is possible and much more. Most methods though have in common that we create a request with the desired URL, optionally hand over parameters and get a response.

There are 2 reasons, why I want to repeat the topic of the previous post and go into more details: On the one hand I did not explain there, how to send the POST parameters, what I want to do here. On the other hand we here use the class HttpWebRequest, since it provides the possibility of storing and managing cookies. This way we can for example use a PHP session, which we will need in a later post.

Let us come to the code, for which System.Net and System.IO have to be included via using:

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://bloggeroliver.bplaced.net/PHPExamples/Post.php");
            string postData = "username=User&password=Secret";
            byte[] data = Encoding.UTF8.GetBytes(postData);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
            request.ContentLength = data.Length;

            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            WebResponse response = (HttpWebResponse)request.GetResponse();
            string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

As example URL I used the PHP script created in the previous post, which expects 2 POST parameters. As one can see, the data in string representation looks as follows:
"Parameter1=Value1&Parameter2=Value2&....ParameterN=ValueN". This string though has to be converted into a Byte array, which we do via Encoding.X.GetBytes(). We replace X with a supported encoding. I chose UTF8 here. One has to be a little bit careful with which encodings are supported by the server. But UTF8 and ANSII should be supported. The coding then also has to be listed in the ContentType.
Finally we create via GetRequestStream() a stream for the request from request and write with this the byte data.
Optionally we then can read the reponse of the request via GetResponse(). In our case the script returns the submitted username and password.

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Hello Oliver, thank you for your posts about C# topics concerning with HTTP, GET, POST, and other things related to this. I'm learning C#, and your blog link was one of the first that appeared through google search.

    I have a few questions if you don't mind...

    1. HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://bloggeroliver.bplaced.net/PHPExamples/Post.php");

    Is it the same as:

    HttpWebRequest request = new HttpWebRequest();
    request.WebRequest.Create("http://bloggeroliver.bplaced.net/PHPExamples/Post.php");

    2. Can you please explain this part? What is a StreamReader and a stream?

    using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }


    //Sorry for noob questions.

    ReplyDelete
    Replies
    1. Hi, no problem at all! Everybody started a beginner at some point - sorry the late response. I hope you made satisfying progress in the meantime.
      To your questions: Your instanciation of the HttpWebRequest gives a syntax error for me - why do you want to do this for me? I would not concentrate on minor coding differences, but instead try to understand the general concept of the code - the exact wording you can always look up. So the point here is to create a request to the desired URL.
      A stream in general is simply a sequence of bytes - for example known when watching a video online, the movie is "streamed", sent as a sequence of bytes. Here the server sends the response in the form of a stream, and we want to read from it. For that we use the class StreamReader, which makes accessing the stream easier with useful methods.

      Delete