Method: HttpHelper#post

Defined in:
lib/common/http/http_helper.rb

#post(url, data = {}, header = {}, file = {}) ⇒ Object

功能:

发送POST请求

参数解释:

  • url http请求的url,比如: hi.baidu.com/,前面的http和后面的/都不能省略

  • data post的数据,Hash格式,键可以是字符串或符号,值可以是字符串或其他

  • header http请求携带的header,比如referer、p3p等,形式与data类似

  • file 支持上传文件,可以传多个,Hash格式,键为参数名,值为文件的本地路径

Example:

Example #1:

# 模拟登录
post "http://passport.baidu.com/?login", {
    :username => 'xxx',
    :password => 'yyy'
}

Example #2:

# 自定义header
login user
post "http://hi.baidu.com/xxx/commit", {
    :ct => 1,
    :cm => 2,
    ........
}, {
    "Myhead" => "okoko"
}

Example #3:

post "http://hi.baidu.com/upload",{
    :xxx => 'yyy'
}
# 环境变量的注入
puts @request.method
puts @response.body
puts @response.header["Content-Length"]
puts @cookies

Example #4:

# 上传文件
post "http://hi.baidu.com/upload",{
    :xxx => 'yyy'
},{},{
    "param_name" => "file_path"
}

Raises:



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/common/http/http_helper.rb', line 70

def post(url,data={},header={},file={})
    #解析成URI
    $myparse = $myparse || URI::Parser.new(:RESERVED=>URI::REGEXP::PATTERN::RESERVED+"%")
    uri = $myparse.parse $myparse.escape(url)
    raise HttpError, "url[#{url}] parse fail! e.g. http://hi.baidu.com/" if uri.scheme.nil? or uri.host.nil? or uri.path.empty?

    # CGI:URI.path 需要加上query部分才能构成一个正常的请求
    path = (uri.query==nil) ? uri.path : uri.path+"?"+uri.query

    # 把header符号变成字符串
    header.each do |k,v|
        if k.class == Symbol
            header[k.to_s] = v.to_s
            header.delete k
        end
    end

    # 初始化Post请求
    req = Net::HTTP::Post.new(path, header)
    req.set_content_type "application/x-www-form-urlencoded" unless req.content_type

    # 发送请求
    send_http req,uri,data,file

end