我想使用net/http来浏览网页,为ruby类添加cookie支持.Cookie必须存储在文件中才能在脚本结束后继续存在.当然我可以阅读规范并编写某种处理程序,使用一些cookie.txt格式等等,但它似乎意味着重新发明轮子.有没有更好的方法来完成这项任务?也许某种类型的帽子类来照顾饼干?
mam*_*lls 42
如果您的服务器返回并期望多个cookie,则接受的答案将不起作用.例如,如果服务器返回一组FedAuth [n] cookie,则可能发生这种情况.如果这会对您产生影响,您可能需要考虑使用以下内容:
http = Net::HTTP.new('https://example.com', 443)
http.use_ssl = true
path1 = '/index.html'
path2 = '/index2.html'
# make a request to get the server's cookies
response = http.get(path)
if (response.code == '200')
    all_cookies = response.get_fields('set-cookie')
    cookies_array = Array.new
    all_cookies.each { | cookie |
        cookies_array.push(cookie.split('; ')[0])
    }
    cookies = cookies_array.join('; ')
    # now make a request using the cookies
    response = http.get(path2, { 'Cookie' => cookies })
end
khe*_*lll 33
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
更新
#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
aku*_*uhn 12
接受的答案不起作用.您需要访问响应标头的内部表示,其中多个set-cookie值分别存储,然后从这些字符串中删除第一个分号后的所有内容并将它们连接在一起.这是有效的代码
r = http.get(path)
cookie = {'Cookie'=>r.to_hash['set-cookie'].collect{|ea|ea[/^.*?;/]}.join}
r = http.get(next_path,cookie)
使用http-cookie,它实现符合RFC的解析和渲染,以及jar.
一个粗略的例子,恰好在登录后重定向:
require 'uri'
require 'net/http'
require 'http-cookie'
uri = URI('...')
jar = HTTP::CookieJar.new
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
  req = Net::HTTP::Post.new uri
  req.form_data = { ... }
  res = http.request req
  res.get_fields('Set-Cookie').each do |value|
    jar.parse(value, req.uri)
  end
  fail unless res.code == '302'
  req = Net::HTTP::Get.new(uri + res['Location'])
  req['Cookie'] = HTTP::Cookie.cookie_value(jar.cookies(uri))
  res = http.request req
end
为什么这样?因为上面的答案是非常不充分的,并且在许多符合RFC的情况下(在我身上发生)不能正常工作,所以如果你想要处理多个特定情况,那么依靠实现所需内容的lib非常强大.
| 归档时间: | 
 | 
| 查看次数: | 43056 次 | 
| 最近记录: |