tags:

views:

799

answers:

3

Hello, I'd like to add cookie support to a ruby class utilizing net/http to browse the web. Cookies have to be stored in a file to survive after the script has ended. Of course I can read the specs and write some kind of a handler, use some cookie.txt format and so on, but it seems to mean reinventing the wheel. Is there a better way to accomplish this task? Maybe some kind of a cooie jar class to take care of cookies?

A: 

You can send receive cookies using headers.

You can store the header in any persistence framework. Whether it is some sort of database, or files.

Matthew Schinckel
+4  A: 

Taken from DZone Snippets

http = Net::HTTP.new('profil.wp.pl', 443)
http.use_ssl = true
path = '/login.html'

# GET request -> so the host can set his cookies
resp, data = http.get(path, nil)
cookie = resp.response['set-cookie'].split('; ')[0]


# POST request -> logging in
data = 'serwis=wp.pl&url=profil.html&tryLogin=1&countTest=1&logowaniessl=1&login_username=blah&login_password=blah'
headers = {
  'Cookie' => cookie,
  'Referer' => 'http://profil.wp.pl/login.html',
  'Content-Type' => 'application/x-www-form-urlencoded'
}

resp, data = http.post(path, data, headers)


# Output on the screen -> we should get either a 302 redirect (after a successful login) or an error page
puts 'Code = ' + resp.code
puts 'Message = ' + resp.message
resp.each {|key, val| puts key + ' = ' + val}
puts data

update

#To save the cookies, you can use PStore
cookies = PStore.new("cookies.pstore")

# Save the cookie  
cookies.transaction do
  cookies[:some_identifier] = cookie
end

# Retrieve the cookie back
cookies.transaction do
  cookie = cookies[:some_identifier] 
end
khelll
>> "Cookies have to be stored in a file to survive after the script has ended"
roddik
-1: the format for cookies given by the server's 'set-cookie' header is *not* the same as the format for cookies sent by the client in the 'cooki' header. Note the different role of semicolons in sections 4.2.2 and 4.3.4 of [RFC2109](http://www.ietf.org/rfc/rfc2109.txt). The "cookie-av" parts of the set-cookie header need to be stripped out, else you risk losing part of your cookie when sending it to the server.
rampion
Update to use PStore for storing the cookies
khelll
Fixed the issue raised by rampion
khelll
A: 

I've used Curb and Mechanize for a similar project. Just enable cookies support and save the cookies to a temp cookiejar... If your using net/http or packages without cookie support built in, you will need to write your own cookie handling.

CodeJoust
I'm on windows where curb won't install :(
roddik