Skip to content

Instantly share code, notes, and snippets.

@joaocarmo
Last active September 7, 2018 17:38
Show Gist options
  • Save joaocarmo/4b70cfa702d824e9b22480cdf2e44447 to your computer and use it in GitHub Desktop.
Save joaocarmo/4b70cfa702d824e9b22480cdf2e44447 to your computer and use it in GitHub Desktop.
Execute HTTP requests with Ruby's net/http
require "net/http"
require "json"
# Execute HTTP requests
# How to use
# http_request({
# "uri" => "...", # Use URI::Parser
# "method" => "...",
# "payload" => "...",
# "headers" => "...",
# })
# returns data, message, status
def http_request(params)
default_params = {
"uri" => "",
"method" => "GET",
"payload" => {},
"headers" => {
"Content-Type" => "application/json; charset=utf-8"
}
}
options = default_params.merge!(params)
uri = options["uri"]
data = nil
message = ""
status = "error"
if !uri.blank?
http_session = Net::HTTP.new(uri.host, uri.port)
if uri.scheme === "https"
http_session.use_ssl = true
http_session.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
begin
http_session.start do |http|
response = http.send_request(
options["method"].upcase,
options["uri"].request_uri,
options["payload"].to_json,
options["headers"]
)
case response
when Net::HTTPSuccess
status = "success"
begin
data = JSON.parse(response.body)
rescue JSON::ParserError => error
message = "not a json response"
end
when Net::HTTPUnauthorized
message = "#{response.message}: username and password set correctly?"
when Net::HTTPServerError
message = "#{response.message}: try again later?"
else
message = response.message
end
end
rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError,
Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => error
message = "#{error}"
end
end
return data, message, status
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment