Module: HttpPoster
- Defined in:
- lib/http_poster.rb
Defined Under Namespace
Classes: Error, HttpError, TimeoutError
Class Method Summary
collapse
-
.build_multipart(params) ⇒ Object
-
.execute(uri, request, opts = {}) ⇒ Object
-
.mime_type(filename) ⇒ Object
-
.parse(response) ⇒ Object
-
.post(url, params = {}, headers = {}, opts = {}) ⇒ Hash/String
核心 POST 方法 ============.
-
.post_form(url, params = {}, headers = {}, opts = {}) ⇒ Object
-
.post_json(url, params = {}, headers = {}, opts = {}) ⇒ Object
-
.post_multipart(url, params = {}, headers = {}, opts = {}) ⇒ Object
POST Multipart(文件上传) params 示例: { file: '/path/to/file.png', purpose: 'image' }.
Class Method Details
.build_multipart(params) ⇒ Object
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
|
# File 'lib/http_poster.rb', line 148
def self.build_multipart(params)
boundary = "----RubyFormBoundary#{SecureRandom.hex(16)}"
parts = []
params.each do |key, value|
if value.is_a?(String) && File.exist?(value)
filename = File.basename(value)
data = File.binread(value)
mime = mime_type(filename)
parts << "--#{boundary}\r\n" \
"Content-Disposition: form-data; name=\"#{key}\"; filename=\"#{filename}\"\r\n" \
"Content-Type: #{mime}\r\n\r\n" \
"#{data}\r\n"
else
parts << "--#{boundary}\r\n" \
"Content-Disposition: form-data; name=\"#{key}\"\r\n\r\n" \
"#{value}\r\n"
end
end
body = parts.join + "--#{boundary}--\r\n"
[body, boundary]
end
|
.execute(uri, request, opts = {}) ⇒ Object
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
|
# File 'lib/http_poster.rb', line 105
def self.execute(uri, request, opts = {})
timeout = opts[:timeout] || 60
open_timeout = opts[:open_timeout] || 10
max_retries = opts[:max_retries] || 2
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme == 'https'
http.open_timeout = open_timeout
http.read_timeout = timeout
retries = 0
begin
response = http.request(request)
parse(response)
rescue Net::OpenTimeout, Net::ReadTimeout => e
retries += 1
if retries <= max_retries
sleep(2 ** retries)
retry
end
raise TimeoutError, "请求超时(已重试 #{max_retries} 次): #{e.message}"
ensure
http.finish if http.started?
end
end
|
.mime_type(filename) ⇒ Object
174
175
176
177
178
179
180
181
182
183
184
185
186
|
# File 'lib/http_poster.rb', line 174
def self.mime_type(filename)
ext = File.extname(filename).downcase
case ext
when '.png' then 'image/png'
when '.jpg', '.jpeg' then 'image/jpeg'
when '.gif' then 'image/gif'
when '.webp' then 'image/webp'
when '.pdf' then 'application/pdf'
when '.txt' then 'text/plain'
when '.json' then 'application/json'
else 'application/octet-stream'
end
end
|
.parse(response) ⇒ Object
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
|
# File 'lib/http_poster.rb', line 131
def self.parse(response)
body = response.body.to_s
code = response.code.to_i
if code >= 400
begin
err = JSON.parse(body)
msg = err.dig('error', 'message') || body
rescue
msg = body
end
raise HttpError, "HTTP #{code}: #{msg}"
end
JSON.parse(body) rescue body
end
|
.post(url, params = {}, headers = {}, opts = {}) ⇒ Hash/String
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
# File 'lib/http_poster.rb', line 43
def self.post(url, params = {}, = {}, opts = {})
uri = URI.parse(url)
content_type = ['Content-Type'] || [:content_type] || 'application/json'
req = Net::HTTP::Post.new(uri)
req['User-Agent'] = ['User-Agent'] || 'ruby-http-poster/1.0'
req['Accept'] = ['Accept'] || 'application/json'
if ['Authorization'] || [:authorization]
req['Authorization'] = ['Authorization'] || [:authorization]
end
case content_type.to_s
when /application\/json/
req['Content-Type'] = 'application/json'
req.body = params.to_json
when /application\/x-www-form-urlencoded/
req['Content-Type'] = 'application/x-www-form-urlencoded'
req.body = URI.encode_www_form(params)
when /multipart\/form-data/
body, boundary = build_multipart(params)
req['Content-Type'] = "multipart/form-data; boundary=#{boundary}"
req.body = body
else
req['Content-Type'] = content_type
req.body = params.is_a?(String) ? params : params.to_json
end
.each do |k, v|
next if %w[Content-Type Authorization User-Agent Accept].include?(k.to_s)
req[k.to_s] = v.to_s
end
execute(uri, req, opts)
end
|
.post_form(url, params = {}, headers = {}, opts = {}) ⇒ Object
91
92
93
94
|
# File 'lib/http_poster.rb', line 91
def self.post_form(url, params = {}, = {}, opts = {})
= .merge('Content-Type' => 'application/x-www-form-urlencoded')
post(url, params, , opts)
end
|
.post_json(url, params = {}, headers = {}, opts = {}) ⇒ Object
85
86
87
88
|
# File 'lib/http_poster.rb', line 85
def self.post_json(url, params = {}, = {}, opts = {})
= .merge('Content-Type' => 'application/json')
post(url, params, , opts)
end
|
.post_multipart(url, params = {}, headers = {}, opts = {}) ⇒ Object
POST Multipart(文件上传)
params 示例: { file: '/path/to/file.png', purpose: 'image' }
98
99
100
101
|
# File 'lib/http_poster.rb', line 98
def self.post_multipart(url, params = {}, = {}, opts = {})
= .merge('Content-Type' => 'multipart/form-data')
post(url, params, , opts)
end
|