vb.net

Send POST values and get response using HttpWebRequest


I have this php file:

<?php

if (isset($_POST['message']))
{
    $msg = $_POST['message'];

    if($msg == "age")
        echo "I am 18";
    else if($msg == "name")
        echo "my name is Jonathan";
    else
        echo "I do not know";

}

?>

I want to make a HttpWebRequest in VB.NET such that if I send the value "age" from a TextBox: enter image description here
To get this following msgbox:
enter image description here

I tried something like this :

Public Sub SendPostData(ByVal site As String, ByVal message As String)

    Dim request As WebRequest
    request = WebRequest.Create(site)
    Dim response As WebResponse
    Dim postData As String = "message=" + message
    Dim data As Byte() = Encoding.UTF8.GetBytes(postData)


    request.Method = "POST"
    request.ContentType = "application/x-www-form-urlencoded"
    request.ContentLength = data.Length

    Dim stream As Stream = request.GetRequestStream()
    stream.Write(data, 0, data.Length)
    stream.Close()

    response = request.GetResponse()
    Dim sr As New StreamReader(response.GetResponseStream())


    MsgBox(sr.ReadToEnd)


End Sub


and I got this :

enter image description here


Any idea why i'm getting that instead of one of the 3 possible message in the php file? ("I am 18", "my name is Jonathan", or "I do not know") ? Please note that I tested the php normally from a html form and it worked, so I wonder why it's not working from the program.


Solution

  • The reason you're getting WHAT you're getting is because you have stated that the FORM content is of a "x-www-form-urlencoded" format AND you have used the POST method and one supposes that whatever is in the cookie (cookie data) is the information that you passed through but it has been encoded by the server before sending.

    I'm not sure how but you should be able to un-encode it too. Alternatively you could use GET as opposed to POST and also if there is only going to be TEXT and no SPECIAL symbols or characters which ACTUALLY require encoding, then maybe you could use a different CONTENT-TYPE that CORRECTLY identifies the type of content that you are sending...

    The following page at W3.org is good reading and explains the differences between the various bits and pieces and how they interact with one another and with the server too.

    Forms ( http://www.w3.org/TR/html401/interact/forms.html)

    How Forms are processed( http://www.w3.org/TR/html401/interact/forms.html#h-17.13.3)