Ruby 2.3.3で
(net/httpsは「このライブラリは Ruby 1.9.2 で net/http にマージされました。 そちらを使ってください。」になっていた)
require 'net/http'
require 'uri'
require 'json'
# get access_token
# (https GET with basic auth)
uri = URI('https://~')
req = Net::HTTP::Get.new(uri)
req.basic_auth('user', 'password')
res = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') { |http|
http.request(req)
}
if res.is_a?(Net::HTTPSuccess)
access_token = JSON.parse(res.body)['access_token']
else
abort "get access_token failed: body=" + res.body
end
# call api
# (https POST with access_token)
post_body_hash = { ~ }
post_body_json = JSON.pretty_generate(post_body_hash)
uri = URI('https://~')
req = Net::HTTP::Post.new(uri)
req['Content-Type'] = req['Accept'] = 'application/json'
req['Authorization'] = 'bearer ' + access_token
req.body = post_body_json
res = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') { |http|
http.request(req)
}
if res.is_a?(Net::HTTPSuccess)
puts JSON.pretty_generate(JSON.parse(res.body))
else
abort "call api failed: body=" + res.body
end