All cookies in WebRequest

For a web service app I use the HandleURL event.
This means that I don’t have access to the CookieManager of a Session.

Is there a way to get all the cookies in a WebRequest?

You can add this method to your App object:

Private Function parseCookies(cookieHeader as String) As Dictionary
  var cookies() as String = cookieHeader.Split( ";" )
  var cookieData as new Dictionary
  for each cookie as String in cookies
    if cookie.IndexOf( "=" ) < 0 then Continue
    
    cookieData.Value( cookie.NthField( "=", 1 ).Trim ) = cookie.NthField( "=", 2 ).Trim
  next
  
  Return cookieData
End Function

Then get the data in your App.HandleURL event:

var cookies as Dictionary = parseCookies( request.Header( "Cookie" ) )
1 Like

But what if some cookie value contains the characters = or ;

I believe cookie data is URLEncoded. I haven’t verified that, I just knocked out some quick code to parse what I see locally to help you get started.

EDIT: From what I’m reading, storing ; is something you just aren’t supposed to do. = is allowed in the value, but not the key, so some modifications will be needed to get the value based on the first occurrence of = rather than a simple split.

2 Likes

Updated method to account for potential = in cookie value:

Private Function parseCookies(cookieHeader as String) As Dictionary
  var cookies() as String = cookieHeader.Split( ";" )
  var cookieData as new Dictionary
  
  var key as String
  for each cookie as String in cookies
    if cookie.IndexOf( "=" ) < 0 then Continue
    
    key = cookie.NthField( "=", 1 )
    cookieData.Value( key.Trim ) = cookie.Right( cookie.Length - key.Length - 1 ).Trim
  next
  
  Return cookieData
End Function
7 Likes

Thank you so much!

Happy to help!