52. HttpWebRequest CookieContainer

This tutorial is a follow up of the previous tutorial and you must have covered Tutorial 51 if you want to understand this. In this tutorial we learn about cookies and the CookieContainer property in HttpWebRequest that allows us to store authentication and preferences. The example we use is logging into a forum and then viewing the user CP.


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§ion=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§ion=login&do=process"
        postReq.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv: 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)
        Dim postresponse As HttpWebResponse

        postresponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
        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

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        WebBrowser1.DocumentText = RichTextBox2.Text
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

        Dim request As HttpWebRequest = DirectCast(WebRequest.Create("http://forums.zybez.net/index.php?app=core&module=usercp"), HttpWebRequest)
        request.CookieContainer = logincookie
        Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
        Dim reader As New StreamReader(response.GetResponseStream())
        Dim theusercp As String = reader.ReadToEnd

        RichTextBox2.Text = theusercp

    End Sub
End Class