Class: Jieshun::Parking::StandardHttpClient
- Inherits:
-
HttpClient
- Object
- HttpClient
- Jieshun::Parking::StandardHttpClient
- Defined in:
- lib/jieshun/parking/http/standard_http_client.rb
Constant Summary collapse
- TIMEOUT =
设置连接和读取的超时时间(以秒为单位)
30
Instance Method Summary collapse
- #post(server_url, content_type, headers, hash) ⇒ Object
-
#post_form(server_url, headers, hash, callback) ⇒ Object
例如,30 秒超时.
- #post_json(server_url, headers, hash, callback) ⇒ Object
Instance Method Details
#post(server_url, content_type, headers, hash) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/jieshun/parking/http/standard_http_client.rb', line 21 def post(server_url, content_type, headers, hash) uri = URI.parse(server_url) req = Net::HTTP::Post.new(uri) headers.each { |k, v| req[k] = v } req["Content-Type"] = content_type Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https', read_timeout: TIMEOUT, open_timeout: TIMEOUT) do |http| if Jieshun::Parking.debug_mode && Jieshun::Parking.logger Jieshun::Parking.logger.debug("Jieshun Parking Request, url: #{server_url}, body: #{JSON.pretty_generate(hash)}") end if content_type == 'application/json' req.body = hash.to_json elsif content_type == 'application/x-www-form-urlencoded' req.set_form_data(hash) else raise RuntimeError.new("Unsupported content type #{content_type}") end res = http.request(req) if Jieshun::Parking.debug_mode && Jieshun::Parking.logger Jieshun::Parking.logger.debug("Jieshun Parking Response #{JSON.pretty_generate(JSON.parse(res.body))}") end successful = res.kind_of?(Net::HTTPSuccess) unless successful = "Got error response from jieshun #{res.status}" Jieshun::Parking.logger.error() raise RuntimeError.new() end json = JSON.parse(res.body) result_code = json['resultCode'] # unless result_code.zero? # message = "Got invalid result code jieshun resultCode: #{result_code}, message: #{json['message']}" # Jieshun::Parking.logger.error(message) # raise RuntimeError.new(json) # end result = Jieshun::Parking::Result.new(result_code.zero?, json.to_hash) yield result end end |
#post_form(server_url, headers, hash, callback) ⇒ Object
例如,30 秒超时
9 10 11 12 13 |
# File 'lib/jieshun/parking/http/standard_http_client.rb', line 9 def post_form(server_url, headers, hash, callback) post(server_url, 'application/x-www-form-urlencoded', headers, hash) do |result| callback.call(result) end end |
#post_json(server_url, headers, hash, callback) ⇒ Object
15 16 17 18 19 |
# File 'lib/jieshun/parking/http/standard_http_client.rb', line 15 def post_json(server_url, headers, hash, callback) post(server_url, 'application/json', headers, hash) do |result| callback.call(result) end end |