Skip to content

HTTP Cookies Example

Andrew Lambert edited this page Jun 9, 2016 · 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:

||example.com|www.example.com|api.example.com|www.example.net| |---|---|---|---|---|---| |example.com|True|True|True|False| |www.example.com|True|True|False|False| |api.example.com|True|False|True|False| |www.example.net|False|False|False|True|

example.com is equivalent to .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", ".example.com")
  MsgBox(cookievalue)
Else
  MsgBox(libcURL.FormatError(curl.LastError))
End If

###Read multiple cookies This example gets 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 cookies.Value(curl.Cookies.Name(i)) = curl.Cookies.Value(i)
    Loop Until i = -1
    ' done
  Else
    MsgBox(libcURL.FormatError(curl.LastError))
  End If
Clone this wiki locally