-
-
Notifications
You must be signed in to change notification settings - Fork 11
HTTP Cookies Example
libcURL provides an optional cookie management system (the "Cookie Engine") which works much like that in a web browser: automatically collecting cookies when they are received and then sending them back when appropriate. The CookieEngine class is the primary means of managing cookies collected by libcURL; you will almost never have cause to manually set cookie headers.
Handling cookies correctly means understanding how libcurl decides to send a particular cookie to a given server. Each cookie is associated with a domain name. This domain name might be fully-qualified (e.g. www.example.com
) or it might omit some or all subdomains (e.g. .example.com
or example.com
). A cookie is sent if its domain "tail" matches the server's domain, for example the server at www.example.com
would receive cookies for .example.com
but not api.example.com
.
This table lists the result of several example comparisons, where True
means the names match:
Result (click "Generate" to refresh) Copy to clipboard
example.com |
www.example.com | api.example.com | ww.wexample.com | |
---|---|---|---|---|
example.com | True | True | True | False |
www.example.com | True | True | False | False |
api.example.com | True | False | True | False |
ww.wexample.com | False | False | False | True |
example.com
is treated as .example.com
for the purposes of comparison.
This example sets a cookie named foo
with the value bar
for all domain names matching .example.com
:
Dim curl As New cURLClient
curl.Cookies.Enabled = True
Call curl.SetCookie("foo", "bar", ".example.com") ' set a cookie
If Not curl.Get("http://www.example.com/") Then
MsgBox(libcURL.FormatError(curl.LastError))
End If
This example gets the value of the cookie named foo
set by www.example.com
:
Dim curl As New cURLClient
curl.Cookies.Enabled = True
If curl.Get("http://www.example.com/") Then
Dim cookievalue As String = curl.GetCookie("foo", "www.example.com")
MsgBox(cookievalue)
Else
MsgBox(libcURL.FormatError(curl.LastError))
End If
This example uses CookieEngine.Lookup to get the names and values of all the cookies set by www.example.com
, and stores them in a Dictionary:
Dim curl As New cURLClient
curl.Cookies.Enabled = True
If curl.Get("http://www.example.com/") Then
Dim cookies As New Dictionary
Dim i As Integer = -1
Do
i = curl.Cookies.Lookup("", "www.example.com", i + 1)
If i > -1 Then
Dim n, v As String
n = curl.Cookies.Name(i)
v = curl.Cookies.Value(i)
cookies.Value(n) = v
End If
Loop Until i = -1
' done
Else
MsgBox(libcURL.FormatError(curl.LastError))
End If
Wiki home | Project page | Bugs | Become a sponsor
Text and code examples are Copyright ©2014-24 Andrew Lambert, offered under the CC BY-SA 3.0 License.