有几个前提
添加到ie的可信站点区域
不能是基于session的cookie
注意url的路径,有些cookie下发是带路径的,获取时不带路径获取不到
#调用时要注意,url最后要有/ 否则某些带路径的cookie获取不到
#获取cookie调用
httpOnlyCookie =GetCookieInternal(New Uri("http://192.168.0.1:10051/web/"), True)
<SuppressUnmanagedCodeSecurity, SecurityCritical, DllImport("wininet.dll", EntryPoint:="InternetGetCookieExW", SetLastError:=True, CharSet:=CharSet.Unicode, ExactSpelling:=True)>
Friend Shared Function InternetGetCookieEx(<[In]> Url As String, <[In]> cookieName As String, <Out> cookieData As StringBuilder, <[In], Out> ByRef pchCookieData As UInteger, flags As UInteger, reserved As IntPtr) As Boolean
End Function
Private Const INTERNET_COOKIE_HTTPONLY As Integer = &H2000
Public Shared Function GetCookieInternal(inuri As Uri, throwIfNoCookie As Boolean) As String
Dim pchCookieData As Integer = 0
Dim url As String
url = inuri.AbsoluteUri
Dim flag As UInteger = INTERNET_COOKIE_HTTPONLY 'NativeMethods.InternetFlags.INTERNET_COOKIE_HTTPONLY;
'Gets the size of the string builder
If (InternetGetCookieEx(url, Nothing, Nothing, pchCookieData, flag, IntPtr.Zero)) Then
pchCookieData = pchCookieData + 1
Dim cookieData As StringBuilder = New StringBuilder(pchCookieData)
'Read the cookie
If (InternetGetCookieEx(url, Nothing, cookieData, pchCookieData, flag, IntPtr.Zero)) Then
DemandWebPermission(inuri)
Return cookieData.ToString()
End If
End If
Dim lastErrorCode As Integer = Marshal.GetLastWin32Error()
If (throwIfNoCookie And (lastErrorCode <> 259)) Then 'NativeMethods.ErrorFlags.ERROR_NO_MORE_ITEMS
Throw New System.ComponentModel.Win32Exception(lastErrorCode)
End If
Return Nothing
End Function
Private Shared Sub DemandWebPermission(inuri As Uri)
Dim uriString As String = UriToString(inuri)
If (inuri.IsFile) Then
Dim localPath As String = inuri.LocalPath
Dim FIP = New FileIOPermission(FileIOPermissionAccess.Read, localPath)
FIP.Demand()
Else
Dim WP = New WebPermission(NetworkAccess.Connect, uriString)
WP.Demand()
End If
End Sub
参考
webBrowser1.Document.Cookie取不到HttpOnly的Cookie,取Cookie不完整
https://blog.csdn.net/smeller/article/details/7022370
Send Cookie through WebBrowser in VB
https://stackoverflow.com/questions/11729596/send-cookie-through-webbrowser-in-vb
InternetGetCookieEx: not working
https://stackoverflow.com/questions/18262653/internetgetcookieex-not-working
© 2019, 新之助meow. 原创文章转载请注明: 转载自http://www.xinmeow.com