我想向一个利用net/http浏览web的ruby类添加cookie支持.Cookies必须存储在文件中,才能在脚本结束后继续存在.当然,我可以阅读规范,编写某种处理程序,使用一些cookie.txt格式等等,但这似乎意味着重新发明轮子.有没有更好的方法来完成这项任务?也许是一种用来处理cookies 的酷罐子课程?
我想向一个利用net/http浏览web的ruby类添加cookie支持.Cookies必须存储在文件中,才能在脚本结束后继续存在.当然,我可以阅读规范,编写某种处理程序,使用一些cookie.txt格式等等,但这似乎意味着重新发明轮子.有没有更好的方法来完成这项任务?也许是一种用来处理cookies 的酷罐子课程?
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