Send POST values and get response using HttpWebReq

2020-07-20 03:49发布

问题:

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:
To get this following msgbox:


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 :


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.

回答1:

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)



回答2:

I have used WebClient to solve a similar problem where i needed to use parameters in the HTTP POST. For your case, a simplified solution like this could help if you play well around with your code; Assuming you have a textbox to capture the age, you could pass it as a variable to the url using this code;

Using client As New WebClient
        Dim postdata = client.UploadString(url, "age")
        MsgBox(postdata) 
End Using


回答3:

Have you considered doing something like this?

Option Strict On
Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim Action As String = "http://www.mywebsite.com/myaction.php"
        PostMessage("submit", "Paul", Action)
    End Sub
    Sub PostMessage(ByVal Type As String, ByVal Value As String, ByVal Action As String)
        Dim TmpFile As String = My.Computer.FileSystem.SpecialDirectories.Temp & "\post.html"
        Using WB As New WebBrowser
            Dim HTML As String = _
                "<html><body>" &
                "<form method=""post"" action=""" & Action & """>" &
                "<input type=""" & Type & """ value=""" & Value & """ />" &
                "</form>" &
                "</body></html>"
            My.Computer.FileSystem.WriteAllText(TmpFile, HTML, False)
            WB.Navigate(TmpFile)
            Do : Application.DoEvents()
            Loop Until WB.ReadyState = WebBrowserReadyState.Complete
            WB.Document.GetElementById(Type).InvokeMember(Type)
            Do : Application.DoEvents()
            Loop Until WB.ReadyState = WebBrowserReadyState.Complete
        End Using
        My.Computer.FileSystem.DeleteFile(TmpFile)
    End Sub
End Class


回答4:

I am experience .net software and knows php also

Never user httpwebrequest and httpwebresponse, 'coz both are out dated

here is the link check properly http://msdn.microsoft.com/en-us/library/debx8sh9%28v=vs.110%29.aspx

It uses WebRequest and WebResponse, add references System.Net and System.Web in your code

And target framework must be 4.0, 4.5 or higher but not to select name containing Client Profile



回答5:

just change this line:

Dim postData As String = "message=" + message

to:

Dim postData As String = "message=" & message

use "&" instead of "+"

Regards...



标签: vb.net