这个问题与How can I get the WebClient to use Cookies?问题中提供的支持cookie的WebClient派生类的使用有关。
我想使用ListBox来...
1)将每个cookie单独显示为“key = value”(For Each循环将所有cookie显示为一个字符串),并且
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
谢谢。
编辑:使用下面的代码,我仍然得到一个单行键=值,而不是我需要显示的单个键=值对:
'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的cookie,而value =多个key = value项的连接。
对于那些感兴趣的人,这里有一些代码来解析值部分:
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
答案 0 :(得分:1)
CookieContainer cookies = new CookieContainer();
// do something to get some cookies
Hashtable domains=
(Hashtable) typeof (CookieContainer)
.GetField("m_domainTable", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(cookies);
foreach (DictionaryEntry domain in domains)
{
CookieCollection domainCookies = cookies.GetCookies(new Uri("http://" + domain.Key));
foreach (Cookie cookie in domainCookies)
{
Console.WriteLine("Domain:{0}, Path:{1}, Port:{2}, Name:{3}, Value:{4}", cookie.Domain, cookie.Path, cookie.Port, cookie.Name, cookie.Value);
}
}
答案 1 :(得分:0)
Cookie
类可以使用Name
和Value
属性,而不是调用只生成适合在HTTP标头中使用的字符串的ToString()
。< / p>
无法枚举cookie容器具有cookie的域,因此您还必须保留域列表,以便您可以使用GetCookies
获取每个域的cookie
答案 2 :(得分:0)
CookieContainer
对象使用GetCookies方法返回CookieCollection
。