This post originated from an RSS feed registered with Agile Buzz
by James Robertson.
Original Post: Dealing with Cookies in the VW Http library
Feed Title: Cincom Smalltalk Blog - Smalltalk with Rants
Feed URL: http://www.cincomsmalltalk.com/rssBlog/rssBlogView.xml
Feed Description: James Robertson comments on Cincom Smalltalk, the Smalltalk development community, and IT trends and issues in general.
The VisualWorks 7.x HTTP code does not have explicit support for HTTP Cookies. This is on the list of things to be addressed - although possibly not by 7.2. At the moment, SOAP Header support is a more difficult problem, and is being dealt with. So in the meantime, what if your application needs to deal with Cookies? Well, adding support isn't terribly hard. I've published a package (used by BottomFeeder) called Http-Access in the public store that - among other things - has support for reading cookies, caching them, and sending them back with requests. Here are the basic steps I took:
First, I added two methods to Net.Response:
getCookies
"Returns all Cookies"
| cookies |
cookies := self fieldsAt: 'set-cookie'.
^cookies collect: [:each | VisualWave.HTTPCookie readFromHeader: each]
There's already a cookie class available, as part of VisualWave. Instead of cloning that into the Net namespace, I just used it. I also wanted to be able to look for cookies by name:
getCookieNamed: aString
^self getCookies detect: [:each | each name asLowercase = aString asLowercase] ifNone: [nil]
There's one more method required - the one I added to VisualWave.Cookie for decoding the cookie from a response. The class doesn't know how to do that, as it was built with the (slightly different) VisualWave framework in mind. Over the next couple of releases, that kind of overlap will disappear, btw. in any event, here's the code that reifies a cooki object:
readFromHeader: cookieAsHeader
| stream |
stream := cookieAsHeader value readStream.
self name: (stream upTo: $=).
self value: (stream upTo: $;).
[stream atEnd]
whileFalse: [| next msg val |
next := (stream upTo: $=) trimBlanks asLowercase.
stream atEnd
ifFalse: [[msg := (next, ':') asSymbol.
val := stream upTo: $;.
[[self perform: msg with: val]
on: MessageNotUnderstood
do: [:ex | ex resume]]].
That handles grabbing the cookies. In my package, I stuff them into a cache object (which I use for conditional-get). Now I have cookies; how do I send them back in a request? I added these two methods to Net.Request:
addCookies: cookies
cookies do: [:each | self addCookie: each]
And that's pretty much it. Your application code needs to actually deal with the cookies in a reasonable way; this code just shows how to grab and send them. Comments or fixes? Send them here