Help us understand the problem. What is going on with this article?

Rubyでhttps・Basic認証・GET/POST・JSONなWeb APIを呼ぶ

More than 3 years have passed since last update.

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
pilot
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした