我正在尝试创建一个名为login 的类,该类登录到网站并将 cookie 保存在cookiecontainer
. 然后我想使用保存在cookiecontainer
其他类中的cookie。我了解如何发出请求并将 cookie 保存在 a 中cookiecontainer
,但是我不知道如何cookiecontainer
在另一个类中使用 。我是否将其cookiecontainer
设为公共共享类型?然后如何从该类的特定实例访问 cookie?
代码:
我正在使用来自http://howtostartprogramming.com/vb-net/vb-net-tutorial-52-httpwebrequest-cookiecontainer/的代码。
Imports System.Net
Imports System.Text
Imports System.IO
Public Class Login
Public shared logincookie As CookieContainer
Private Sub Login()
Dim postData As String = "poststring"
Dim tempCookies As New CookieContainer
Dim encoding As New UTF8Encoding
Dim byteData As Byte() = encoding.GetBytes(postData)
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("website"), HttpWebRequest)
postReq.Method = "POST"
postReq.KeepAlive = True
postReq.CookieContainer = tempCookies
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
End Sub
End Class