Skip to content

HTTP Cookies Example

Andrew Lambert edited this page Mar 16, 2017 · 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. 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.

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

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 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
Clone this wiki locally