Created
March 19, 2011 21:10
-
-
Save olivere/877805 to your computer and use it in GitHub Desktop.
em-http-request with capturing and passing cookies on redirects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment