OK, net/http!
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
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