【发布时间】:2010-05-16 18:02:07
【问题描述】:
此问题与How can I get the WebClient to use Cookies? 问题中提供的支持 cookie 的 WebClient 派生类的使用有关。
我想使用 ListBox 来...
1) 将每个 cookie 单独显示为“key=value”(For Each 循环将它们全部显示为一个字符串),并且
2) 能够显示所有 cookie,无论它们来自哪个域(此处为“www.google.com”):
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
'How to display cookies as key/value in ListBox?
'PREF=ID=5e770c1a9f279d5f:TM=1274032511:LM=1274032511:S=1RDPaKJKpoMT9T54
For Each mycc In webClient.cc.GetCookies(New Uri(URL))
ListBox1.Items.Add(mycc.ToString)
Next
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
谢谢。
编辑:使用下面的代码,我仍然得到一个单行 key=value 而不是我需要显示的单个 key=value 对:
'How to display cookies as key=value in ListBox?
'still displayed as 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)
'MessageBox.Show(mycookie.Name & vbTab & mycookie.Value)
Next
编辑:原来 Google 返回了一个带有 key=PREF 和 value=多个 key=value 项的串联的 cookie。
对于那些感兴趣的人,这里有一些通过值部分解析的代码:
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
【问题讨论】: