Last active
August 29, 2015 14:20
-
-
Save svkmax/b2e96762cac3ecfb0e88 to your computer and use it in GitHub Desktop.
RequestBuilder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module RequestBuilder | |
DEBUG = false | |
require 'net/http' | |
require 'json' | |
require 'uri' | |
require 'mime-types' | |
require 'openssl' | |
require 'response_handler' | |
#uri_string - URI | |
#req_type - Post/Put/Get/Delete etc | |
#headers - Hash of headers | |
#returns response | |
def self.do_request(uri_string, req_type, headers, body) | |
req = build_request(uri_string, req_type, headers, body) | |
i = 0 | |
begin | |
make_request(URI(uri_string), req) | |
rescue SocketError | |
i += 1 | |
retry if i<2 | |
raise SocketError | |
end | |
end | |
require 'net/http/post/multipart' | |
def self.do_post_form_request(uri_string, form_fields_hash, token=nil) | |
file_name = File.basename(form_fields_hash['file'].path) | |
form_fields_hash['file'] = UploadIO.new(form_fields_hash['file'], MIME::Types.type_for(file_name).first.content_type, file_name) | |
url = URI.parse(uri_string) | |
req = Net::HTTP::Post::Multipart.new url.path, form_fields_hash | |
req.add_field("Token", token) if token | |
res = Net::HTTP.start(url.host, url.port, {:use_ssl => url.port == 443}) do |http| | |
http.request(req) | |
end | |
return res | |
end | |
private | |
# We need to define place where we will modify body to json/xml | |
#for now here body already modified | |
def self.build_request(uri_string, req_type, headers, body) | |
req = "Net::HTTP::#{req_type}".constantize.new(uri_string) | |
headers = {"REST-API-Version" => "0.1.0"}.update(headers) | |
headers.each_pair {|head,value| req.add_field(head, value)} | |
req.body = body if body | |
return req | |
end | |
#retry mechanism is needed | |
# this is a simplest retry mechanism | |
def self.make_request(uri, req, retry_request=true) | |
Rails.logger.debug("URI: #{uri.inspect}") | |
Rails.logger.debug("REQ: #{req.body.inspect}") | |
response = Net::HTTP.start(uri.host, uri.port, {:use_ssl => uri.port == 443}) do |http| | |
http.request(req) #returns a response | |
end | |
Rails.logger.debug("RESPONSE: #{response.body}") | |
ResponseHandler.check_status(response) | |
return response | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment