ruby em-http-request在重定向上捕获和传递cookie

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby em-http-request在重定向上捕获和传递cookie相关的知识,希望对你有一定的参考价值。

# Gemfile
source "http://rubygems.org"
gem 'eventmachine', '~>1.0.0.beta.3'
gem 'em-synchrony', '~>0.3.0.beta.1'
gem 'em-http-request', '~>1.0.0.beta3'
gem 'addressable', :require => 'addressable/uri'


# Capturing and passing cookies on redirects
require "rubygems"
require "bundler/setup"

require 'eventmachine'
require 'em-synchrony'
require 'em-synchrony/em-http'
require 'pp'

# Use a URL that does some redirects and requires cookies to send a special result
URL = "..."

# Borrowed from HTTParty, a great rubygem from John Nunemaker (thanks!)
class CookieHash < Hash #:nodoc:
  CLIENT_COOKIES = %w{path expires domain path secure HTTPOnly HttpOnly}
  
  def add_cookies(value)
    case value
    when Hash
      merge!(value)
    when String
      value.split('; ').each do |cookie|
        array = cookie.split('=')
        self[array[0].to_sym] = array[1]
      end
    else
      raise "add_cookies only takes a Hash or a String"
    end
  end

  def to_cookie_string
    delete_if { |k, v| CLIENT_COOKIES.include?(k.to_s) }.collect { |k, v| "#{k}=#{v}" }.join("; ")
  end
end

class CookiePersist
  def self.cookies
    Thread.current[:cookies] ||= []
  end

  def self.cookie_hash
    CookieHash.new.tap { |hsh|
      cookies.uniq.each { |c| hsh.add_cookies(c) }
    }
  end

  def self.request(head, body)
    head['cookie'] = cookie_hash.to_cookie_string
    #puts "Sending cookies: #{head['cookie']}"
    [head, body]
  end

  def self.response(resp)
    resp
  end
end

EM.synchrony do
  conn = EM::HttpRequest.new(URL)
  conn.use CookiePersist
  http = conn.aget(:redirects => 5)

  http.headers { |head|
    CookiePersist.cookies << head[EM::HttpClient::SET_COOKIE]
  }

  http.callback {
    puts http.response if http.response =~ /NEW_ITEM/
    EM.stop
  }

  http.errback  { 
    puts 'err'
    EM.stop
  }
end

以上是关于ruby em-http-request在重定向上捕获和传递cookie的主要内容,如果未能解决你的问题,请参考以下文章

捕获要在重定向页上显示的错误

如何使用 PHP 在重定向页面上使用 Google Analytics 进行跟踪?

使用 JavaScript/jQuery 在重定向上发送 POST 数据? [复制]

在重定向期间切换协议

Magento安装卡在重定向循环中[关闭]

PHP 而不是 HTML 中的 <form> 从脚本发送表单并停留在重定向页面上?