Skip to content

HTTP Cookies Example

Andrew Lambert edited this page Jan 14, 2023 · 23 revisions

Remarks

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.

Domain name matching

Handling cookies correctly means understanding how libcurl decides to send a particular cookie to a given server. Just like a web browser, libcurl enforces a same-origin policy for cookies. Each cookie is associated with a domain name, its "origin". 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 origin domain "tail" matches the domain being connected to, for example the server at www.example.com would receive cookies indexed under .example.com but not under api.example.com.

This table lists the result of several example comparisons, where True means the names match:

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.

Examples

Set a cookie

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
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

Read a cookie

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

Read multiple cookies

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 Not curl.Get("http://www.example.com/") Then
    MsgBox(libcURL.FormatError(curl.LastError))
  End If
  
  Dim cookies As New Dictionary
  Dim i As Integer = curl.Cookies.Lookup("", "www.example.com")
  Do Until i = -1
    Dim n, v As String
    n = curl.Cookies.Name(i)
    v = curl.Cookies.Value(i)
    cookies.Value(n) = v
    i = curl.Cookies.Lookup("", "www.example.com", i + 1)
  Loop
  ' done
Clone this wiki locally