Skip to content

Instantly share code, notes, and snippets.

@zh
Forked from natritmeyer/tiniest_http_client.rb
Last active August 29, 2015 14:11
Show Gist options
  • Save zh/acae0e453c13244f16d4 to your computer and use it in GitHub Desktop.
Save zh/acae0e453c13244f16d4 to your computer and use it in GitHub Desktop.
require 'net/http'
class HttpClient
def initialize(base_url, username = nil, password = nil)
@base_url = base_url
@username = username
@password = password
end
def get(path, headers = {})
uri = URI.parse("#{@base_url}#{path}")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
request.basic_auth @username, @password unless @username.nil?
headers.keys.each do |key|
request[key] = headers[key]
end
http.request(request)
end
def post(path, headers = {}, body = "")
uri = URI.parse("#{@base_url}#{path}")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri)
request.basic_auth @username, @password unless @username.nil?
headers.keys.each do |key|
request[key] = headers[key]
end
request.body = body
http.request(request)
end
def put(path, headers = {}, body = "")
uri = URI.parse("#{@base_url}#{path}")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Put.new(uri.request_uri)
request.basic_auth @username, @password unless @username.nil?
headers.keys.each do |key|
request[key] = headers[key]
end
request.body = body
http.request(request)
end
def delete(path)
uri = URI.parse("#{@base_url}#{path}")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Delete.new(uri.request_uri)
request.basic_auth @username, @password unless @username.nil?
http.request(request)
end
end
require 'tiniest_http_client'
@http_client = HttpClient.new "http://my_host:8080", "username", "password"
#GET
@http_client.get "/my_resource/1"
@http_client.get "/my_resource/1", {"Accept" => "application/json"}
#POST
@http_client.post "/my_resource/1", {"Content-Type" => "application/xml", "Accept" => "application/xml"}, "this is the body"
#PUT
@http_client.put "/my_resource/1"
@http_client.put "/my_resource/1", {"Content-Type" => "application/xml", "Accept" => "application/xml"}, "this is the body"
#DELETE
@http_client.delete "/my_resource/1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment