Class: Infosimples::Data::HTTP
- Inherits:
-
Object
- Object
- Infosimples::Data::HTTP
- Defined in:
- lib/infosimples/data/http.rb
Overview
Infosimples::Data::HTTP exposes common HTTP routines that can be used by the Infosimples::Data API client.
Class Method Summary collapse
-
.prepare_multipart_data(payload) ⇒ String
Prepare the multipart data to be sent via a :multipart request.
-
.request(options = {}) ⇒ String
Perform an HTTP request with support for multipart requests.
Class Method Details
.prepare_multipart_data(payload) ⇒ String
Prepare the multipart data to be sent via a :multipart request.
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/infosimples/data/http.rb', line 60 def self.prepare_multipart_data(payload) boundary = 'randomstr' + rand(1_000_000).to_s # a random unique string content = [] payload.each do |param, value| content << '--' + boundary content << "Content-Disposition: form-data; name=\"#{param}\"" content << '' content << value end content << '--' + boundary + '--' content << '' [boundary, content.join("\r\n")] end |
.request(options = {}) ⇒ String
Perform an HTTP request with support for multipart requests.
16 17 18 19 20 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 |
# File 'lib/infosimples/data/http.rb', line 16 def self.request( = {}) uri = URI([:url]) method = [:method] || :get payload = [:payload] || {} timeout = [:http_timeout] headers = { 'User-Agent' => Infosimples::Data::USER_AGENT } case method when :get uri.query = URI.encode_www_form(payload) req = Net::HTTP::Get.new(uri.request_uri, headers) when :post req = Net::HTTP::Post.new(uri.request_uri, headers) req.set_form_data(payload) when :multipart req = Net::HTTP::Post.new(uri.request_uri, headers) boundary, body = prepare_multipart_data(payload) req.content_type = "multipart/form-data; boundary=#{boundary}" req.body = body else fail Infosimples::Data::ArgumentError, "Illegal HTTP method (#{method})" end http = Net::HTTP.new(uri.hostname, uri.port) http.use_ssl = true if (uri.scheme == 'https') http.open_timeout = timeout http.read_timeout = timeout + 10 http.max_retries = 0 if http.respond_to?(:max_retries) # fix max_retries res = http.request(req) res.body rescue Net::OpenTimeout, Net::ReadTimeout raise Infosimples::Data::Timeout end |