net/http with cookies?

B

Brian Le Roy

I'm attempting to navigate a website that requires a login. In
particular, does anyone have a solution that utilizes cookies? Looking
at the included Net/http library, it doesn't appear to be supported - or
at least it isn't mentioned. Thanks in advance!

brian
 
D

daz

Brian said:
I'm attempting to navigate a website that requires
a login. In particular, does anyone have a solution
that utilizes cookies? Looking at the included
Net/http library, it doesn't appear to be supported - or
at least it isn't mentioned. Thanks in advance!

Hi Brian,

I assume when you've logged in, your details are saved
in the cookie and you bypass the next login by providing
the saved cookie.

A cookie is sent as a Hash value ['Cookie'] in the headers
along with the request and received as a Hash value with
a key of ['Set-Cookie'] along with the response.


The snippet below will obtain a cookie from google
as a non-login example.
The commented hdrs['Cookie'] = 'blah' is where you
would provide a previously saved cookie.


More information than you need about cookies here:
[HTTP State Management Mechanism]
http://www.faqs.org/rfcs/rfc2109.html


Hope that's enough to get you going.


daz


#-----------------------------------------
require 'net/http'

http = Net::HTTP.new('www.google.com')
http.start do |sess|
# hdrs = {} # or {'Some_header' => 'some content'}
# hdrs['Cookie'] = 'invalid;cookie;string--garbage1'
hdrs = nil # send no headers
resp = sess.get('/', hdrs)
case resp.code.to_i
when 200, 302
resp.each {|r| p r}; puts '+++++'
cookie = resp['Set-Cookie']
if cookie
puts cookie.split(/;/)
puts '-----', resp.body
else
puts 'No cookie received'
end
else
puts "Error - code(#{resp.code}) - #{resp.msg}"
end
end
#-----------------------------------------

### e.g. OUTPUT:
=begin
["date", "Tue, 30 Aug 2005 18:59:47 GMT"]
["content-type", "text/html"]
["server", "GWS/2.1"]
["content-length", "217"]
["set-cookie", "PREF=ID=c728 ... ; path=/; domain=.google.com"]
["location", xxxx://www.google.co.uk/cxfer?c=.../]
+++++
PREF=ID=c728abd36b89aeae:CR=1:TM=1125428 ... qJwJjksFGLTNGLaZ
expires=Sun, 17-Jan-2038 19:14:07 GMT
path=/
domain=.google.com
-----
<HTML><HEAD><TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="xxxx://www.google.co.uk/cxfer?c=...;prev=/">here</A>.

</BODY></HTML>
=end
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,176
Messages
2,570,950
Members
47,504
Latest member
SherryFerr

Latest Threads

Top