51. HttpWebRequest POST Method

Part 1

Part 2

In this tutorial we cover using the HttpWebRequest POST Method to send data to an online HTML form. The HttpWebRequest is used like the web browser and allows you to act like a web browser without the bulky web browser object being in your application. I’d like to apologize about first of all the sound quality, I’ll be sure to fix the blowing into the mic I don’t know what caused that. I’d also like to apologize for stuttering quite frequently but this tutorial was recorded when I was tired.

Code

Imports System.Net
Imports System.Text
Imports System.IO

Public Class Form1

    Dim logincookie As CookieContainer

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim postData As String = "referer=http%3A%2F%2Fforums.zybez.net%2Findex.php%3Fapp%3Dcore%26module%3Dglobal%26section%3Dlogin&username=" & TextBox1.Text & "&password=" & TextBox2.Text & "&rememberMe=1"
        Dim tempCookies As New CookieContainer
        Dim encoding As New UTF8Encoding
        Dim byteData As Byte() = encoding.GetBytes(postData)

        Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("http://forums.zybez.net/index.php?app=core&module=global&section=login&do=process"), HttpWebRequest)
        postReq.Method = "POST"
        postReq.KeepAlive = True
        postReq.CookieContainer = tempCookies
        postReq.ContentType = "application/x-www-form-urlencoded"
        postReq.Referer = "http://forums.zybez.net/index.php?app=core&module=global&section=login&do=process"
        postReq.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)"
        postReq.ContentLength = byteData.Length

        Dim postreqstream As Stream = postReq.GetRequestStream()
        postreqstream.Write(byteData, 0, byteData.Length)
        postreqstream.Close()
        Dim postresponse As HttpWebResponse

        postresponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
        tempCookies.Add(postresponse.Cookies)
        logincookie = tempCookies
        Dim postreqreader As New StreamReader(postresponse.GetResponseStream())

        Dim thepage As String = postreqreader.ReadToEnd

        RichTextBox1.Text = thepage

    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        WebBrowser1.DocumentText = RichTextBox1.Text
    End Sub

End Class