Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually add a cookie to Mechanize state?

Tags:

I'm working in Ruby, but my question is valid for other languages as well.

I have a Mechanize-driven application. The server I'm talking to sets a cookie using JavaScript (rather than standard set-cookie), so Mechanize doesn't catch the cookie. I need to pass that cookie back on the next GET request.

The good news is that I already know the value of the cookie, but I don't know how to tell Mechanize to include it in my next GET request.

like image 555
fearless_fool Avatar asked Mar 30 '10 23:03

fearless_fool


1 Answers

I figured it out by extrapolation (and reading sources):

agent = Mechanize.new ... cookie = Mechanize::Cookie.new(key, value) cookie.domain = ".oddity.com" cookie.path = "/" agent.cookie_jar.add(cookie) ... page = agent.get("https://www.oddity.com/etc") 

Seems to do the job just fine.

update

As @Benjamin Manns points out, Mechanize now wants a URL in the add method. Here's the amended recipe, making the assumption that you've done a GET using the agent, and that the last page visited is the domain for the cookie (saves a URI.parse()):

agent = Mechanize.new ... cookie = Mechanize::Cookie.new(key, value) cookie.domain = ".oddity.com" cookie.path = "/" agent.cookie_jar.add(agent.history.last.uri, cookie) 
like image 74
fearless_fool Avatar answered Nov 24 '22 06:11

fearless_fool