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

推荐答案

摘自DZone Snippets

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

Ruby相关问答推荐

RSpec:为什么 `instance_double` 可以与 StandardError 一起使用,但不能与其他异常类一起使用?

如何在 Ruby 中正确编写代码?以便它产生正确的输出?

Ruby ERB 类给出未定义的局部变量或方法,但 erb 解析良好

.nil?、.blank? 之间的区别?和.empty?

如何修改 Ruby gem

Ruby:子字符串到一定长度,也到子字符串中的最后一个空格

Ruby |= 赋值运算符

Ruby 中的 STDIN 和 $stdin 有什么区别?

在基于值的哈希数组上唯一

在单个 node 上使用 XPath 返回所有 node 中的元素

Ruby 的排序方法使用哪种算法?

理解|| Ruby 中 If 条件中的 OR 运算符

卸载所有 gem Ruby 2.0.0

有没有办法从该实例内部为 Ruby 类的实例创建方法?

在 RSpec 测试期间 suppress 控制台输出

`respond_to?` 与 `respond_to_missing?`

如何在没有 Rails 的情况下使用 RSpec?

如何合并 Ruby 哈希

工厂女孩 - 目的是什么?

从 'mm/dd/yyyy' 格式解析 ruby​​ DateTime