[url=http://httparty.rubyforge.org/]Httparty[/url]是一个很好用的基于Ruby的net库的gem,自身非常小巧,用法很灵活。
但是他有个毛病,就是发送完http请求之后返回的是http小的html部分,而不是消息头,比如set-cookie,status code,location等。
为了满足需求,又要保持Httparty源代码和官方同步,下面写了这个补丁:
"httpartyHack.rb"
使用Httparty的时候需要:
如果你需要这个补丁的话,请在include Httparty之后:
此时通过Httparty的get或者post方法得到的便是完整的response,而且该response增加了一个header方法,可以通过header方法访问该response的头,类型为Hash。
但是他有个毛病,就是发送完http请求之后返回的是http小的html部分,而不是消息头,比如set-cookie,status code,location等。
为了满足需求,又要保持Httparty源代码和官方同步,下面写了这个补丁:
"httpartyHack.rb"
#
# To change this template, choose Tools | Templates
# and open the template in the editor.
module HttpartyHack
def self.included(base)
class << base
alias_method :_send_request,:send_request
include HackMethods
#private_class_method :send_request
private :send_request
end
end
end
module HackMethods
def self.included(base)
#p "HackMethods been #{base} included"
end
def send_request(method, path, options={}) #:nodoc:
raise ArgumentError, 'only get, post, put and delete methods are supported' unless %w[get post put delete].include?(method.to_s)
raise ArgumentError, ':headers must be a hash' if options[:headers] && !options[:headers].is_a?(Hash)
raise ArgumentError, ':basic_auth must be a hash' if options[:basic_auth] && !options[:basic_auth].is_a?(Hash)
uri= URI.parse("#{base_uri}#{path}")
existing_query = uri.query ? "#{uri.query}&" : ''
uri.query= if options[:query].blank?
existing_query + default_params.to_query
else
existing_query + (options[:query].is_a?(Hash) ? default_params.merge(options[:query]).to_query : options[:query])
end
klass = Net::HTTP.const_get method.to_s.downcase.capitalize
request = klass.new(uri.request_uri)
request.body= options[:body].is_a?(Hash) ? options[:body].to_query : options[:body] unless options[:body].blank?
basic_auth = options.delete(:basic_auth) || @auth
request.initialize_http_header headers.merge(options[:headers] || {})
# note to self: self, do not put basic auth above headers because it removes basic auth
request.basic_auth(basic_auth[:username], basic_auth[:password]) if basic_auth
response = http(uri).request(request)
class<<response
attr :header
end
response
end
end
使用Httparty的时候需要:
include Httparty
如果你需要这个补丁的话,请在include Httparty之后:
include HttpartyHack
此时通过Httparty的get或者post方法得到的便是完整的response,而且该response增加了一个header方法,可以通过header方法访问该response的头,类型为Hash。