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

Rubyでプロキシ経由でWebAPIを使うときのメモ

More than 3 years have passed since last update.

RubyでWebAPIを使うにあたって

  • プロキシ経由でどうやって接続するの?
  • httpsは?
  • POSTは?
  • レスポンスヘッダやステータスコードもみたいんだけど・・・

みたいなことがよくわからなかったのでメモ。

require 'net/https'
require 'uri'

## プロキシの設定
proxy_addr = 'hogehoge.com'
proxy_port = 8080
proxy_user = 'user_name'
proxy_pass = 'user_password'



## 接続先URLを指定してパース
URL = "http://hogehoge/fuga"
uri = URI.parse(URL)


## リクエストのヘッダーとボディを設定する。POSTメソッドを指定
req = Net::HTTP::Post.new(uri.path)

# リクエストヘッダの指定(指定しない場合は省略可)
req["Content-Type"] = "application/json"
req["Accept"] = "application/json"

# ボディとなるjsonファイルの読み込み(指定しない場合は省略可)
file = File.read("token_req.json")

# リクエストボディを挿入(指定しない場合は省略可)
req.body = file

# 今回はjson形式のテキストファイルを直接挿入しているけど、
# Rubyのハッシュをセットしたい場合には
# req.set_form_data({'name' => 'hoge', 'content' => 'hogehoge'})
# みたいな感じでも書けるらしい


## httpsプロトコル接続用のインスタンスを作成
https = Net::HTTP.new(uri.host, uri.port,proxy_addr, proxy_port, proxy_user, proxy_pass)
https.use_ssl = true     # HTTPSで接続(https使わないなら省略可)
https.verify_mode = OpenSSL::SSL::VERIFY_NONE     #証明書チェックを無効化(https使わないなら省略可)


## 接続を開始
res = https.start do
  https.request(req)
end

## レスポンスステータスを表示
puts res.code

## レスポンスヘッダを表示
res.each_header do |name, val|
  puts "#{name}: #{val}"
end

## レスポンスボディを表示
puts res.body
Why do not you register as a user and use Qiita more conveniently?
  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
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