Skip to content

Instantly share code, notes, and snippets.

@ywjno
Last active December 29, 2015 04:09
Show Gist options
  • Save ywjno/7612592 to your computer and use it in GitHub Desktop.
Save ywjno/7612592 to your computer and use it in GitHub Desktop.
Net::HTTP Example
# encoding: utf-8
require "net/http"
require "uri"
class Connection
VERB_MAP = {
:get => Net::HTTP::Get,
:post => Net::HTTP::Post,
:put => Net::HTTP::Put,
:delete => Net::HTTP::Delete
}
attr_reader :http
def initialize(url)
uri = URI.parse(url)
@http = Net::HTTP.new(uri.host, uri.port)
end
def request(method, path, params, initheader)
method = method.to_sym
case method
when :get
full_path = params ? path_with_params(path, params) : path
request = VERB_MAP[method].new(full_path, initheader)
when :post
request = VERB_MAP[method].new(path, initheader)
if 'application/json' == initheader['Content-Type']
params = params.to_json if params.is_a?(Hash)
request.body = params
else
request.set_form_data(params)
end
else
request = VERB_MAP[method].new(path, initheader)
request.set_form_data(params)
# or like it
# request.form_data = params
end
@http.request(request)
end
private
def path_with_params(path, params)
encoded_params = URI.encode_www_form(params)
[path, encoded_params].join("?")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment