Skip to content

Instantly share code, notes, and snippets.

@ryandotsmith
Created March 17, 2015 03:26
Show Gist options
  • Save ryandotsmith/d58e542a0d30978ea105 to your computer and use it in GitHub Desktop.
Save ryandotsmith/d58e542a0d30978ea105 to your computer and use it in GitHub Desktop.
OK, net/http!
require 'json'
require 'net/http'
require 'thread'
require 'openssl'
require 'uri'
module Okhttp
class Conn
def initialize(url)
@url = URI(url)
@conn_mutex = Mutex.new
end
def post(path, body)
make_req(Net::HTTP::Post, path, body)
end
def put(path, body)
make_req(Net::HTTP::Put, path, body)
end
def get(path, param={})
path = path + "?" + URI.encode_www_form(params) unless params.empty?
make_req(Net::HTTP::Get, path)
end
def delete(path)
make_req(Net::HTTP::Delete, path)
end
private
def make_req(type, path, body=nil)
conn do |c|
req = type.new([@url.request_uri, path].compact.join)
req['Content-Type'] = 'application/json'
req.body = body
resp = c.request(req)
[Integer(resp.code), resp.to_hash, resp.body]
end
end
def conn
@conn ||= establish_conn
@conn_mutex.synchronize do
begin
return yield(@conn)
rescue => e
@conn = nil
raise(e)
end
end
end
def establish_conn
Net::HTTP.new(@url.host, @url.port).tap do |c|
c.open_timeout = timeout
c.read_timeout = timeout
c.set_debug_output($stdout) if ENV['DEBUG']
if @url.scheme == 'https'
c.use_ssl = true
c.verify_mode = OpenSSL::SSL::VERIFY_PEER
end
end
end
end
end
c = Okhttp::Conn.new('https://httpbin.org')
status, headers, body = c.post('/post', JSON.dump({hello: 'world'}))
puts body
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment