Skip to content

Instantly share code, notes, and snippets.

@matthuhiggins
Created September 8, 2011 18:58
Show Gist options
  • Select an option

  • Save matthuhiggins/1204315 to your computer and use it in GitHub Desktop.

Select an option

Save matthuhiggins/1204315 to your computer and use it in GitHub Desktop.
require 'uri'
require 'net/http'
require 'net/https'
module Curl
class Easy
attr_accessor :uri, :headers, :follow_location, :max_redirects
attr_accessor :response, :redirect_count
def initialize
self.headers = {}
self.follow_location = false
self.max_redirects = 0
end
def http_post(body)
while_redirecting do |path|
http.post(path_and_query, body, headers)
end
end
def perform
while_redirecting do |path|
http.get(path, headers)
end
end
def url=(url)
self.uri = URI.parse url
end
def useragent=(useragent)
headers['User-Agent'] = useragent
end
def body_str
response.body
end
def response_code
response.code
end
private
def while_redirecting
redirects = 0
path = path_and_query
begin
self.response = yield(path)
if response.kind_of?(Net::HTTPRedirection)
redirects += 1
path = redirect_url(response)
end
end while response.kind_of?(Net::HTTPRedirection) && follow_location && redirects <= max_redirects && path
end
def http
@http ||= begin
http = Net::HTTP.new(uri.host, uri.port)
if uri.is_a?(URI::HTTPS)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
http
end
end
def path_and_query
result = uri.path
result << "?#{uri.query}" if uri.query
result
end
def redirect_url(response)
response['location'] || response.body.match(/<a href=\"([^>]+)\">/i)[1]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment