Any sample for HTTP POST Function written in VB.NET?

wonder_gal

Active member
Joined
Jun 5, 2006
Messages
34
Programming Experience
1-3
Hi,

I'm learning to code a HTTP POST function in my page. Can anyone with experience show me a sample skeleton here? Many thanks. :)
 
hey wonder_gal, i knocked up this demo for you:

VB.NET:
Dim req As Net.HttpWebRequest
Dim resp As Net.HttpWebResponse
Dim s As IO.Stream
Dim sr As IO.StreamReader

Try
    'create byte array of post data
    Dim enc As New System.Text.ASCIIEncoding()
    Dim postData As String = "name=bob&age=12"
    Dim data As Byte() = enc.GetBytes(postData)
    
    'create request object
    'req = Net.WebRequest.Create("[URL]http://www.vbdotnetforums.com/[/URL]")
    req = Net.WebRequest.Create("[URL]http://ukpc200290/test.php[/URL]")
    req.ContentType = "application/x-www-form-urlencoded"
    req.ContentLength = data.Length
    req.Method = "POST"
    
    'get request stream to write post data too
    s = req.GetRequestStream()
    s.Write(data, 0, data.Length)
    s.Close()
    
    'get response
    resp = req.GetResponse()
    
    'check response data
    If resp.StatusCode = Net.HttpStatusCode.OK Then
        MessageBox.Show("Success")
        
        sr = New IO.StreamReader(resp.GetResponseStream())
        MessageBox.Show(sr.ReadToEnd())
    End If
    
Catch ex As Exception
    MessageBox.Show("Error Occurred")
Finally
    If sr IsNot Nothing Then sr.Close()
    If resp IsNot Nothing Then resp.Close()
End Try
And script you could test against in PHP would be like this:

VB.NET:
<?php

if(isset($_POST['name']) && isset($_POST['age'])) {
    echo "OK";
}

?>
Good luck
 
You should also know that the WebClient class uses POST for it's Upload methods if the target is HTTP protocol, and similar GET for it's Download methods.
 
Hi mafrosis, thanks alot for sharing the skeleton, I've gone through it, it's understandable.... great...... :D

Btw, anyone else has different skeleton to brief me? Hope to see more different sets of methods here. Thanks. ;)
 
Back
Top