Skip to content

Instantly share code, notes, and snippets.

@foomin10
Last active August 29, 2015 14:17
Show Gist options
  • Save foomin10/36f5c009948261eada39 to your computer and use it in GitHub Desktop.
Save foomin10/36f5c009948261eada39 to your computer and use it in GitHub Desktop.
[Ruby] 簡単に `http_get(url, data_hash)` したり `http_post` するための21行 ref: http://qiita.com/MizuiroFolder/items/ca286ae227d3c2f80712
http_get('http://www.example.org/index.html') #=> #<Net::HTTPOK 200 OK>
http_get(uri)
http_post(uri, {'foo'=> 0, 'bar'=> 1})
http_get(uri, {'foo'=> 0, 'bar'=> 1})
http_get(uri, 'foo=0&bar=1')
require 'net/http'
def http_get(uri, data=nil, header=nil, proxy=nil)
uri = URI(uri) unless uri.is_a?(URI)
proxy = URI(proxy) unless proxy.is_a?(URI)
http = Net::HTTP.new(uri.host, uri.port,
proxy.host, proxy.port, proxy.user, proxy.password)
uri.query = data.is_a?(String) ? data : URI.encode_www_form(data) if data
http.start {|h|
h.get(uri.request_uri, header)
}
end
def http_post(uri, data=nil, header=nil, proxy=nil)
uri = URI(uri) unless uri.is_a?(URI)
proxy = URI(proxy) unless proxy.is_a?(URI)
http = Net::HTTP.new(uri.host, uri.port,
proxy.host, proxy.port, proxy.user, proxy.password)
data = URI.encode_www_form(data) unless data.is_a?(String)
http.start {|h|
h.post(uri.request_uri, data, header)
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment