1

我正在使用赞助者gem 来创建 curl 请求。这是代码

    s = Patron::Session.new
    s.connect_timeout = 15
    s.timeout = 15
    s.base_url = API_URL
    s.headers['Date'] = DATE_HEADER
    s.headers['Accept'] = 'application/xml'
    s.headers['Content-Type'] = 'application/json'
    s.headers['Authorization'] = "API" + " " + auth_token
    response = s.delete(uri)
    response.status

我怎样才能得到这个 gem 发出的原始 curl 请求?

4

1 回答 1

2

你不能。错误...您可以通过 monkey_patchingPatron::Session.request方法,并在处理之前产生请求。但请注意,这不是“libcurl”请求,因为它只存在于 C 代码中,它是一个Patron::Request实例。

另外,请注意您的猴子补丁可能随时中断,因为您必须重写整个方法!

yield您在处理对 libcurl 的请求之前添加了一个,因此您有机会通过一个块来获取它。

req = nil
response = s.delete(uri) do |r|
  req = r
end
# now req should be your request instance.

这是补丁的提示:

class Patron::Session

# You have to patch all the standard methods to accept a block
def get(url, headers = {}, &block)
  request(:get, url, headers, &block)
end
# do the same for get_file, head, delete, put, put_file, post, post_file and post_multipart


def request(action, url, headers, options = {}, &block)
  # If the Expect header isn't set uploads are really slow
  headers['Expect'] ||= ''

  req = Request.new
  req.action                 = action
  req.headers                = self.headers.merge headers
  req.timeout                = options.fetch :timeout,               self.timeout
  req.connect_timeout        = options.fetch :connect_timeout,       self.connect_timeout
  req.max_redirects          = options.fetch :max_redirects,         self.max_redirects
  req.username               = options.fetch :username,              self.username
  req.password               = options.fetch :password,              self.password
  req.proxy                  = options.fetch :proxy,                 self.proxy
  req.proxy_type             = options.fetch :proxy_type,            self.proxy_type
  req.auth_type              = options.fetch :auth_type,             self.auth_type
  req.insecure               = options.fetch :insecure,              self.insecure
  req.ignore_content_length  = options.fetch :ignore_content_length, self.ignore_content_length
  req.buffer_size            = options.fetch :buffer_size,           self.buffer_size
  req.multipart              = options[:multipart]
  req.upload_data            = options[:data]
  req.file_name              = options[:file]

  base_url = self.base_url.to_s
  url = url.to_s
  raise ArgumentError, "Empty URL" if base_url.empty? && url.empty?
  uri = URI.join(base_url, url)
  query = uri.query.to_s.split('&')
  query += options[:query].is_a?(Hash) ? Util.build_query_pairs_from_hash(options[:query]) : options[:query].to_s.split('&')
  uri.query = query.join('&')
  uri.query = nil if uri.query.empty?
  url = uri.to_s
  req.url = url

  yield req if block_given? # added line

  handle_request(req)
end
end
于 2012-11-06T09:46:07.930 回答