LoginSignup
8
10

More than 5 years have passed since last update.

[Ruby] 簡単に `http_get(url, data_hash)` したり `http_post` するための21行

Last updated at Posted at 2015-03-15

Net::HTTP はなにげにめんどくさい。

というかアプローチの仕方がいろいろあってどうするのが一番いいか忘れがち。

なのでメソッド化して毎回の get/post を楽にしよう、と思ったのだがどこまで抽象化してどこまで対応すればよいか悩んだ。その結果がこれ。

require 'net/http'

def http_get(uri, data=nil, header=nil, proxy=nil)
  uri = URI(uri) unless uri.is_a?(URI)
  proxy = URI(proxy) unless proxy.is_a?(URI)
  http = Net::HTTP.new(uri.host, uri.port,
    proxy.host, proxy.port, proxy.user, proxy.password)
  uri.query = data.is_a?(String) ? data : URI.encode_www_form(data) if data
  http.start {|h|
    h.get(uri.request_uri, header)
  }
end

def http_post(uri, data=nil, header=nil, proxy=nil)
  uri = URI(uri) unless uri.is_a?(URI)
  proxy = URI(proxy) unless proxy.is_a?(URI)
  http = Net::HTTP.new(uri.host, uri.port,
    proxy.host, proxy.port, proxy.user, proxy.password)
  data = URI.encode_www_form(data) unless data.is_a?(String)
  http.start {|h|
    h.post(uri.request_uri, data, header)
  }
end
  • GET/POST メソッドのリクエストまで
  • http オブジェクトは外で使わないと思うので、すぐにリクエストしてレスポンスオブジェクトを返すものにした
  • ボディ付き GET(クエリとして用いる)
  • GET/POST のボディが文字列でなかったら(Hash、二重配列)、 URI.encode_www_form で変換
  • リクエストする URI やプロキシは、文字列か URI オブジェクトで指定できる
example
http_get('http://www.example.org/index.html') #=> #<Net::HTTPOK 200 OK>

http_get(uri)

http_post(uri, {'foo'=> 0, 'bar'=> 1})

http_get(uri, {'foo'=> 0, 'bar'=> 1})

http_get(uri, 'foo=0&bar=1')

Net::HTTP.Proxy (第一引数が nil だと通常の Net::HTTP オブジェクトを返す)とかやってみたけど結局 Net::HTTP.new に落ち着いた。

ボディ付き GET(クエリとして用いる)のやり方がググってもわからなかったけど、(たぶん)正しい方法はこれっぽい……「query= にぶっこんで path の代わりに request_uri を用いる」。

8
10
1

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
8
10