vb.net如何获取网页的cookie
1个回答
展开全部
这个问题有点意思,但题主表意不明,确切的说应该分Web端和客户端两种情况。
想来问到这个问题的不应该是开发Web端的,说说客户端的吧:
1、HttpWebRequest.CookieContainer
Cookies通过HttpResponse传给客户端,通过HttpRequest传回服务端,因此你可以
设置Response.Cookies集合的值修改Cookie
1
Response.Cookies("MyCookie")("Data") = myCookie
通过读取Request.Cookies集合的值得到Cookies的值
1
myCookie =Request.Cookies("MyCookie")("Data") & ""
2、本人自编的一个函数,放到一个模块里直接调用即可:
Dim myCookie As String
Public Function LoginAnGetCookie(ByRef sUser As String, ByRef sPass As String) As String()
On Error Resume Next
REM 登录网站并获得cookie
Dim url As String = "网站地址"
Dim postData As String = "sUser=" & sUser & "&sPass=" & sPass '假设传值的是这样的,实际中可用Fiddler抓取。
Dim wc As System.Net.WebClient = New System.Net.WebClient
Rem wc.Headers.Add("Cookie", myCookie) '可讲第一次获得的Cookie赋值给myCookie,然后在此处传值给网站即可
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded")
wc.Headers.Add("UserAgent", "Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10)")
Dim sHtml As String = wc.UploadString(url, "POST", postData)
Dim arrAllKeys() As String = wc.ResponseHeaders.AllKeys
Dim sCookies As String = "Set-Cookie"
For i As Integer = 0 To arrAllKeys.Length - 1
If arrAllKeys(i).Equals("Set-Cookie") Then sCookies = wc.ResponseHeaders.Get(i)
Next i
Return New String() {sHtml, sCookies} '返回二维数组,其中LoginAnGetCookie(0)是网页源代码,LoginAnGetCookie(1)是登录后的Cookie
End Function
想来问到这个问题的不应该是开发Web端的,说说客户端的吧:
1、HttpWebRequest.CookieContainer
Cookies通过HttpResponse传给客户端,通过HttpRequest传回服务端,因此你可以
设置Response.Cookies集合的值修改Cookie
1
Response.Cookies("MyCookie")("Data") = myCookie
通过读取Request.Cookies集合的值得到Cookies的值
1
myCookie =Request.Cookies("MyCookie")("Data") & ""
2、本人自编的一个函数,放到一个模块里直接调用即可:
Dim myCookie As String
Public Function LoginAnGetCookie(ByRef sUser As String, ByRef sPass As String) As String()
On Error Resume Next
REM 登录网站并获得cookie
Dim url As String = "网站地址"
Dim postData As String = "sUser=" & sUser & "&sPass=" & sPass '假设传值的是这样的,实际中可用Fiddler抓取。
Dim wc As System.Net.WebClient = New System.Net.WebClient
Rem wc.Headers.Add("Cookie", myCookie) '可讲第一次获得的Cookie赋值给myCookie,然后在此处传值给网站即可
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded")
wc.Headers.Add("UserAgent", "Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10)")
Dim sHtml As String = wc.UploadString(url, "POST", postData)
Dim arrAllKeys() As String = wc.ResponseHeaders.AllKeys
Dim sCookies As String = "Set-Cookie"
For i As Integer = 0 To arrAllKeys.Length - 1
If arrAllKeys(i).Equals("Set-Cookie") Then sCookies = wc.ResponseHeaders.Get(i)
Next i
Return New String() {sHtml, sCookies} '返回二维数组,其中LoginAnGetCookie(0)是网页源代码,LoginAnGetCookie(1)是登录后的Cookie
End Function
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询