# How to handle cookie with ruby

**URL:** <https://www.ruby-forum.com/t/how-to-handle-cookie-with-ruby/115918>\
**Category:** Ruby\
**Created:** [September 30, 2007, 10:18am UTC](https://www.ruby-forum.com/t/how-to-handle-cookie-with-ruby/115918 "2007-09-30T10:18:46Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![leondu](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/b2d939/32.png) [@leondu](https://www.ruby-forum.com/u/leondu)\
**Post date:** [September 30, 2007, 10:18am UTC](https://www.ruby-forum.com/t/how-to-handle-cookie-with-ruby/115918/1 "2007-09-30T10:18:46Z")

</div>

Hi all, I dont know how to handle cookie with ruby.  
the problem is I want to fetch content from a website which need login  
first.  
I use the http.post to do the login and seemed works well, but when I  
went  
to the index page, still I got the login first message.  
so, any suggestions?

---------------------below is my code---------------------------  
require ‘net/http’  
require ‘cgi’  
require ‘iconv’

def fetch\_content  
Net::HTTP.start (‘domain’ ) do |server|  
id = CGI.escape(“id” )  
passwd = CGI.escape(“pw” )  
params = “id=#{id}&pwpwd=#{passwd}”  
resp = server.post2(’/login.php?’ , params,headers)

```
# I got a 200 OK, the resp.body shows that the login is successful

params = ""
resp = server.post2('/index.php' , params,headers)
# after checking the resp.body , the index page still says I need to

```

login  
end  
end

---

<div class="post-metadata">

**Author:** ![leondu](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/b2d939/32.png) [@leondu](https://www.ruby-forum.com/u/leondu)\
**Post date:** [September 30, 2007, 2:11pm UTC](https://www.ruby-forum.com/t/how-to-handle-cookie-with-ruby/115918/2 "2007-09-30T14:11:07Z")

</div>

leon du wrote:

> Hi all, I dont know how to handle cookie with ruby.  
> the problem is I want to fetch content from a website which need login  
> first.  
> I use the http.post to do the login and seemed works well, but when I went  
> to the index page, still I got the login first message.  
> so, any suggestions?

I guess you should try e.g. Mechanize:

[http://mechanize.rubyforge.org/mechanize/](http://mechanize.rubyforge.org/mechanize/)

which is designed for just this kind of thing.

---

<div class="post-metadata">

**Author:** ![leondu](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/b2d939/32.png) [@leondu](https://www.ruby-forum.com/u/leondu)\
**Post date:** [October 1, 2007, 5:51am UTC](https://www.ruby-forum.com/t/how-to-handle-cookie-with-ruby/115918/3 "2007-10-01T05:51:38Z")

</div>

thanks a lot, mechanize seemed to be the solution 🙂

2007/9/30, mortee [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):
