很多人不知道如何去获取IE浏览器中的Cookie信息,其实获取Cookie的方式很简单,只需要调用InternetGetCookie这个API就可以获得了。

InternetGetCookie的声明方式如下:

Private Declare Function InternetGetCookie Lib "wininet.dll" Alias "InternetGetCookieA" (ByVal lpszUrlName As String, ByVal lpszCookieName As String, ByVal lpszCookieData As String, lpdwSize As Long) As Boolean

我们要获取www.baidu.com这个域名之下的Cookie信息可以这么写:

Dim buffer As String * 8096
If InternetGetCookie("http://www.baidu.com", vbNullString, buffer, 8096) Then
    MsgBox "获取到的Cookie信息如下: " & vbCrLf & buffer
End If

获取结果:

获取到的Cookie信息如下: 
bdshare_firstime=1385336980826; sug=3; sugstore=1; BD_TMP_CK=true; BAIDUID=F1F6DA77AD0E469EEF3301C98F1CB0A1:FG=1; cflag=65535%3A1; BAIDU_WISE_UID=wapp_1385534156727_907; locale=zh; bdime=0; NBID=D3EEB391CF4DCDA2ED0B6035E872886D:FG=1

<font color=red>在用InternetGetCookie获取Cookie信息有个缺点,它无法获得带有HTTP_ONLY标记的Cookie。</font>
针对这个问题的解决办法是使用InternetGetCookie这个API的扩展版InternetGetCookieEx来获取,不过它也有问题,对某些版本的IE支持不怎么好。

InternetGetCookieEx的声明方式如下:

Private Const INTERNET_COOKIE_HTTPONLY As Integer = 8192
Private Declare Function InternetGetCookieEx Lib "wininet.dll" Alias "InternetGetCookieExA" (ByVal url As String, ByVal cookieName As String, ByVal cookieData As String, ByRef size As Integer, ByVal flags As Integer, ByVal pReserved As Long) As Boolean

调用方式也差不多:


Dim buffer As String * 8096
If InternetGetCookieEx("http://www.baidu.com", vbNullString, buffer, 8096, INTERNET_COOKIE_HTTPONLY, 0) Then
    MsgBox "获取到的Cookie信息如下: " & vbCrLf & buffer
End If

获取结果:

获取到的Cookie信息如下: 
bdshare_firstime=1385336980826; sug=3; sugstore=1; BD_TMP_CK=true; BAIDUID=F1F6DA77AD0E469EEF3301C98F1CB0A1:FG=1; cflag=65535%3A1; BAIDU_WISE_UID=wapp_1385534156727_907; locale=zh; bdime=0; NBID=D3EEB391CF4DCDA2ED0B6035E872886D:FG=1; BDUSS=EdwblA4akE5NjV-N3RPZFdjcW52VkJQQXBvbXhRMm5PaEXucy05am1MYkdjY0pTQVFBQUFBJCQAAAAAAAAAAAEAAAXDmn4UdDJubgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMbkmlLS5JpSe

这两个API各有优缺点,具体使用哪个得看具体情况选择了。

标签: none

添加新评论