LoginSignup
84
96

More than 5 years have passed since last update.

net/httpsでWebAPIにPOSTリクエストを投げる

Last updated at Posted at 2015-09-20

色々調べてAPIを使ってみた時のメモ書きです。
POSTをする必要があったので、色々と悩ましかったです。

require 'net/https'

class TestController < ApplicationController

  def apipost

    uri = URI.parse("https://example.jp/foo/ber/piyo/1/")
    http = Net::HTTP.new(uri.host, uri.port)

    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE

    req = Net::HTTP::Post.new(uri.path)
    req.set_form_data({'name' => 'hoge', 'content' => 'hogehoge'})

    res = http.request(req)

  end
end

require 'net/https'
今回はhttps通信を使うのでこちらです。
http通信の'net/http'もあります。
library net/https

uri = URI.parse("https://example.jp/foo/ber/piyo/1/")
hostやpathを分けてわたせる様になります。
singleton method URI.parse

http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

http.use_ssl = trueは必ずtrueを指定するようです。
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
は証明書の検証をするかしないかの設定みたいです。今回はしないように指定してます。
【ruby】net/httpでPOSTリクエスト(https)投げてみる。
module OpenSSL::SSL

req = Net::HTTP::Post.new(uri.path)
req.set_form_data({'name' => 'hoge', 'content' => 'hogehoge'})

ここでPOSTの設定をしています。
req.set_form_data({'name' => 'hoge', 'content' => 'hogehoge'})
の部分は状況によって変わると思うのでAPIに合わせてお願いします。
Net::HTTP Cheat Sheet

res = http.request(req)

リクエストを実行して、レスポンスが無事帰ってこれば成功です。

深いJSON

↓文字列をJSONに変換
result = ActiveSupport::JSON.decode(res.body)
↓中身
=> {"a"=>"0",
 "b"=>
  [{"c"=>"0",
    "d"=>
     [{"e"=>"1",
       "f"=>"9",
       "g"=>"1",
       "h"=>"1",
       "i"=>"0",
       "j"=>"0",
       "k"=>"0",
       "l"=>"1",
       "m"=>"0",
       "n"=>"1"}],
    "o"=>
     [{"p"=>"0",
       "q"=>"-1",
       "r"=>"0",
       "s"=>"2"}],
    "t"=>["1"],
    "u"=>"hoge"}]}

初めて見た時はさっぱりわかりませんでした。
文字列"hoge"を取り出したい場合は、
result["b"][0]["u"]としてあげると取り出せます。
この[hash][array][hash]の並びが見えてくるまでひたすら打ち込んでました。

84
96
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
84
96