LoginSignup
3
2

More than 5 years have passed since last update.

Rubyでsimpleにhttp requestを送る

Posted at

Rubyでシンプルにhttp Requestを送ってresponseで条件分岐

  • ちょっとリクエストを試してみようみたいな時にコピペで使える情報です。
  • URIに日本語とか混じると意外とどうするんだったか忘れてしまうのでそれも一緒に載せました。

目標

  1. net/http, uri, jsonなどのrubyの基本的なmoduleを深く考えずとりあえず使えるようになること。
  2. statusコードとかで条件分岐出来るようになる。

①Get(レスポンス => json)

require 'net/http'
require 'json'
class Map
  def geocode(address)
    # domain+pathをuriとする
    uri = URI("https://maps.googleapis.com/maps/api/geocode/json")
    # (日本語が混じっていたりする場合 => URI.parse(URI.escape("https://ほげ/)) )

    # queryはわかりやすいように分けて設定する(uriにそのまま含めることも可能)
    query = {address: address.gsub(" ", ""), key: "YOUR_API_KEY" }
    uri.query = URI.encode_www_form(query)

    # 実際にgetリクエストを飛ばす
    res = Net::HTTP.get_response(uri)

    # statusコードを確認
    puts res.code

    data = JSON.parse(res.body.to_s)
    lat = data["results"][0]["geometry"]["location"]["lat"]
    lng = data["results"][0]["geometry"]["location"]["lng"]
    [lat,lng]
  end
end

# 実行
a = Map.new
puts a.geocode("東京都世田谷区")
# => 35.6465721, 139.6532473

responseについてはNet::HttpResponseオブジェクトが帰ってくる。具体的には以下のような値を得ることが出来る。

# Headers
res['Set-Cookie']            # => stringで返ってくる
res.get_fields('set-cookie') # => Array
res.to_hash['set-cookie']    # => Array
puts "Headers: #{res.to_hash.inspect}"

# Status
puts res.code       # => '200'(integer)
puts res.message    # => 'OK'(string)
puts res.class.name # => 'HTTPOK'(string)

# Body
puts res.body if res.response_body_permitted?

参考: https://ruby-doc.org/stdlib-2.5.1/libdoc/net/http/rdoc/Net/HTTP.html

3
2
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
3
2