Module: Baidu::Support::Request

Includes:
Baidu::Support
Included in:
OAuth::Client, OAuth::RESTClient, PCS::Client
Defined in:
lib/baidu/support/request.rb

Constant Summary collapse

MAX_REDIRECT_LIMIT =

最多重定向次数

10

Instance Method Summary collapse

Instance Method Details

#get(path, query = {}, options = {}) {|segment| ... } ⇒ Object

发送 GET 请求

Parameters:

  • path (String)
  • query (Hash) (defaults to: {})

    自动清理 value 为 nil 的数据

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :site (String)
  • :raw (Boolean)

    直接返回 response.body

  • :headers (Hash)

Yields:

  • (segment)

    可选,如果提供 block,则以流的方式获取内容


19
20
21
22
23
24
25
26
27
28
29
# File 'lib/baidu/support/request.rb', line 19

def get(path, query={}, options={}, &block)
  url  = build_url path, query, options[:site]
  req = Net::HTTP::Get.new(url, options[:headers])
  if block_given?
    request(req) do |resp|
      resp.read_body &block
    end
  else
    request(req, nil, options[:raw])
  end
end

#post(path, query = {}, body = {}, options = {}) ⇒ Object

发送 POST 请求

Parameters:

  • path (String)
  • query (Hash) (defaults to: {})

    自动清理 value 为 nil 的数据

  • body (Hash) (defaults to: {})

    自动清理 value 为 nil 的数据,可以包含响应 #read 的对象,如:File

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :site (String)

37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/baidu/support/request.rb', line 37

def post(path, query={}, body={}, options={})
  uri = build_url path, query, options[:site]
  Util.clean_params(body)
  if body.select{ |_, v| v.respond_to? :read }.empty?
    req = Net::HTTP::Post.new uri
    req.body = (body.empty? ? nil : Util.encode_params(body))
  else
    require 'net/http/post/multipart'
    body.each { |k, v| body[k] = UploadIO.new v, 'application/octet-stream' if v.respond_to? :read }
    req = Net::HTTP::Post::Multipart.new uri, body
  end
  request req
end