Module: HttpHelper

Included in:
MtopHelper::MtopV4, MyTest, SuperTest
Defined in:
lib/common/http/http_helper.rb

Overview

实现HTTP协议的支持,可以在action或case中调用

  • 封装 Net:HTTP 和 Net:HTTPS

  • 模拟浏览器的Cookie策略,不完全实现,不支持Expire(没必要)

  • 上下文环境的保持,request & response

  • 编码转换(统一使用gbk)

  • Referer、User-Agent等的自动填入

  • 打印可读日志

Instance Method Summary collapse

Instance Method Details

功能:

清空当前cookie

参数解释:

Example:

get "http://www.baidu.com/"
clear_cookie        # => 清空cookie
get "http://hi.baidu.com/"


226
227
228
# File 'lib/common/http/http_helper.rb', line 226

def clear_cookie
    @cookies = {}
end

#delete(url, data = nil, header = nil) ⇒ Object

功能:

发送DELETE请求未实现,有需求吗?

参数解释:

Example:



212
213
214
# File 'lib/common/http/http_helper.rb', line 212

def delete(url,data=nil,header=nil)
    #TODO
end

#do_encodeObject

功能:

参见dont_encode



268
269
270
271
272
273
274
275
276
# File 'lib/common/http/http_helper.rb', line 268

def do_encode
    if block_given? 
        @dont_encode = false
        yield
        @dont_encode = true
    else
        @dont_encode = false
    end
end

#dont_encodeObject

功能:

指定不要进行转码

参数解释:

Example:

Example #1: block方式

dont_encode do
    get "..."
    post "..."
end
# 凡是块里面的请求都不会有转码,但是块外面的代码仍然可以

Example #2: 非block方式

get "http://www.baidu.com/"
# 返回页面经过转码,转成GBK
dont_encode
get "http://www.baidu.com/"
# 返回页面在任何情况下都不会做任何转码
# ...
do_encode
# 恢复转码方式
get "http://www.baidu.com/"
# 返回页面经过转码,转成GBK


256
257
258
259
260
261
262
263
264
# File 'lib/common/http/http_helper.rb', line 256

def dont_encode 
    if block_given? 
        @dont_encode = true
        yield
        @dont_encode = false
    else
        @dont_encode = true
    end
end

#download(uri, path = nil) ⇒ Object



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/common/http/http_helper.rb', line 170

def download(uri, path=nil)
    begin
        if path
            file_name = path + uri.split('/').last
            file_name.sub(/\/\//, '/')
        else
            file_name = uri.split('/').last
        end

        file_content = get uri
        #puts file_name
        File.open(file_name, "w+") do |file|
            file.binmode # must be in binary mode
            file.write file_content
            file.rewind
        end
    rescue => err
        puts err
        return ''
    end
end

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

功能:

发送GET请求

参数解释:

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

  • data 数据将被编码并附在url的后面,Hash格式,键可以是字符串或符号,值可以是字符串或其他

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

Example:

Example #1:

# 注意url要写全,带上协议头"http",以及路径,若是根路径末尾要加"/"
get "http://www.baidu.com/"

Example #2:

# 支持https
get "https://passport.baidu.com/"

Example #3:

get "http://www.baidu.com/"
# 环境变量的注入
puts @request.method
puts @response.body
puts @response.header["Content-Length"]
puts @cookies

Example #4:

# 可自定义 HTTP Header
get "http://hi.baidu.com/",{
    :q => "空间",
    :t => "haha"
},{
    "Cookie" => "BDUSS=xxx;",
    "Referer" => "google.com"
}

Example #5:

# 带参数
get "https://passport.baidu.com/",{
    :name => "walle",
    :password => "1111"
}

Raises:



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/common/http/http_helper.rb', line 138

def get(url,data={},header={})
    #解析成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

    # 将data转成url中的参数
    path << "?" if data.size>0 && !path.include?("?")
    data.each do |k,v|
        path << "&" if !path.end_with?("&") && !path.end_with?("?")
        path << k.to_s + "=" + CGI::escape(v.to_s)
    end

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

    # 初始化Get请求
    req = Net::HTTP::Get.new(path, header)

    # 发送请求
    send_http req,uri

end

#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

功能:

打印当前HTTP请求返回的content,可用于调试

参数解释:

Example:

get "http://www.baidu.com/"
print_body
#=> <html><head><meta http-equiv=Content-Type content="text/html;charset=gb2312"><title>百度一下,你就知道      </title>.....(省略)


289
290
291
# File 'lib/common/http/http_helper.rb', line 289

def print_body
    puts @response.body unless @response.nil?
end

功能:

打印当前HTTP请求返回的所有Header,可用于调试

参数解释:

Example:

get "http://www.baidu.com/"
print_head
#=> {"date"=>["Sun, 27 Dec 2009 12:04:29 GMT"], "server"=>["BWS/1.0"], "content-length"=>["3657"], "content-type"=>["text/html;charset=gb2312"], "cache-control"=>["private"], "expires"=>["Sun, 27 Dec 2009 12:04:29 GMT"], "set-cookie"=>["BAIDUID=95C50755A927A287A68E2014CEF4CF1E:FG=1; expires=Sun, 27-Dec-39 12:04:29 GMT; path=/; domain=.baidu.com"], "p3p"=>["CP=\" OTI DSP COR IVA OUR IND COM \""]}


304
305
306
# File 'lib/common/http/http_helper.rb', line 304

def print_head
    puts @response.to_hash unless @response.nil?
end

#put(url, data = "", header = nil, file = nil) ⇒ Object

功能:

发送PUT请求未实现,有需求吗?

参数解释:

Example:



200
201
202
# File 'lib/common/http/http_helper.rb', line 200

def put(url,data="",header=nil,file=nil)
    #TODO
end