Question [WebClient] How to read cookies individually?

littlebigman

Well-known member
Joined
Jan 5, 2010
Messages
75
Programming Experience
Beginner
Hello

This question pertains to the use of a cookie-capable WebClient derived class.

I'd like to use a ListBox to...

1) display each cookie individually as "key=value" (the For Each loop displays all of them as one string), and

2) be able to display all cookies, regardless of the domain from which they came ("www.google.com", here).

The problem with the code below, is that it returns all the cookies as a single value with key=PREF:

VB.NET:
Imports System.IO
Imports System.Net

Public Class Form1
  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim webClient As New CookieAwareWebClient
    Const URL = "http://www.google.com"
    Dim response As String

    response = webClient.DownloadString(URL)
    RichTextBox1.Text = response

[COLOR="Blue"]
    'How to display cookies as key=value in ListBox?
    'Returns key=PREF value=ID=c1c024db87787437:TM=1274083167:LM=1274083167:S=ZsG7BXqbCe7yVgJY
    Dim mycookiecollection As CookieCollection
    mycookiecollection = webClient.cc.GetCookies(New Uri(URL))
    Dim mycookie As Cookie
    For Each mycookie In mycookiecollection
        ListBox1.Items.Add(mycookie.Name & vbTab & mycookie.Value)
    Next
[/COLOR]
  End Sub
End Class

Public Class CookieAwareWebClient
	Inherits WebClient
	
	Public cc As New CookieContainer()
	Private lastPage As String
	
	Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest
	    Dim R = MyBase.GetWebRequest(address)
	    If TypeOf R Is HttpWebRequest Then
	        With DirectCast(R, HttpWebRequest)
	            .CookieContainer = cc
	            If Not lastPage Is Nothing Then
	                .Referer = lastPage
	            End If
	        End With
	    End If
	    lastPage = address.ToString()
	    Return R
	End Function
End Class

Is there a better way than regexing through the value above to extract individual cookies?

Thank you.
 
1. Your current code does that, PREF is a single cookie that happens to have key-value pairs in its value string. These pairs also doesn't follow the HttpCookie subkey pattern but you could work around that.
VB.NET:
For Each ck As Cookie In cookies
    Dim ht As New Web.HttpCookie(ck.Name, ck.Value.Replace(":", "&"))
    If ht.HasKeys Then
        Debug.WriteLine(ht.Name)
        For Each key In ht.Values.AllKeys
            Debug.WriteLine(vbTab & key & vbTab & ht.Values(key))
        Next
    Else
        Debug.WriteLine(ht.Name & vbTab & ht.Value)
    End If
Next
2. no, you have to specify for which url. If you want to monitor everything that goes on with the requests/responses for debugging I recommend a tool such as this: Fiddler Web Debugger - A free web debugging tool
 
Back
Top