ingalcala
ingalcala

Reputation: 1845

How do I save cookies when I request a new page in one session?

I have this code, and I login successfully:

require 'mechanize'
require 'logger'
agent = Mechanize.new{|a| a.log = Logger.new(STDERR) }
agent.read_timeout = 60
def add_cookie(agent, uri, cookie)
  uri = URI.parse(uri)
  Mechanize::Cookie.parse(uri, cookie) do |cookie|
    agent.cookie_jar.add(uri, cookie)
  end
end
page = agent.get "http://www.webpage.com"
form = page.forms.first
form.correo_ingresar = "user"
form.password = "password"
page = agent.submit form
myarray = page.body.scan(/SetCookie\(\"(.+)\", \"(.+)\"\)/)

After I login I do not get redirected, so I looked at the webpage and Java is the one redirecting me, but if I use page = agent.get("http://webpage.com") all session cookies are deleted. And I have to login again , and it is a cycle because I don't get past that. I already tried several recommendations like ignore_discard

Upvotes: 2

Views: 1206

Answers (2)

pguardiario
pguardiario

Reputation: 55002

It looks like you have the right code to add the cookie but forgot to call it. At the end try:

myarray.each{|line| add_cookie agent, 'http://www.sistemasaplicados.com.mx', "#{line[0]}=#{line[1]}"}

Upvotes: 3

Phrogz
Phrogz

Reputation: 303421

Mechanize automatically receives, stores, and sends cookies when using the same instance to get new pages.

  1. Are you certain that the site is actually sending cookies?
  2. Have you confirmed that Mechanize is really not sending the cookies? (Have you inspected the request headers it sends?)
  3. You said "Java is [...] redirecting me"; did you really mean JavaScript?

Upvotes: 1

Related Questions