Ruby 1.9.3 リファレンスマニュアル > ライブラリ一覧 > net/httpライブラリ

library net/http

要約

汎用データ転送プロトコル HTTP を扱うライブラリです。 実装は [RFC2616] に基きます。

使用例

ウェブサーバからドキュメントを得る (GET)

例1: GET して 表示するだけ

require 'net/http'
Net::HTTP.get_print 'www.example.com', '/index.html'

例2: URI を使う

require 'net/http'
require 'uri'
Net::HTTP.get_print URI.parse('http://www.example.com/index.html')

例3: より汎用的な例

require 'net/http'
require 'uri'

url = URI.parse('http://www.example.com/index.html')
res = Net::HTTP.start(url.host, url.port) {|http|
  http.get('/index.html')
}
puts res.body

例4: 上の例よりさらに汎用的な例

require 'net/http'

url = URI.parse('http://www.example.com/index.html')
req = Net::HTTP::Get.new(url.path)
res = Net::HTTP.start(url.host, url.port) {|http|
  http.request(req)
}
puts res.body

フォームの情報を送信する (POST)

require 'net/http'
require 'uri'

#例1: POSTするだけ
res = Net::HTTP.post_form(URI.parse('http://www.example.com/search'),
                          {'q'=>'ruby', 'max'=>'50'})
puts res.body

#例2: 認証付きで POST する
res = Net::HTTP.post_form(URI.parse('http://jack:pass@www.example.com/todo.cgi'),
                          {'from'=>'2005-01-01', 'to'=>'2005-03-31'})
puts res.body

#例3: より細かく制御する
url = URI.parse('http://www.example.com/todo.cgi')
req = Net::HTTP::Post.new(url.path)
req.basic_auth 'jack', 'pass'
req.set_form_data({'from'=>'2005-01-01', 'to'=>'2005-03-31'}, ';')
res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
case res
when Net::HTTPSuccess, Net::HTTPRedirection
  # OK
else
  res.value
end

プロクシ経由のアクセス

Net::HTTP.Proxy はプロクシ経由での接続を行なうクラスを 生成して返します。このクラスは Net::HTTP と同じ メソッドを持ち、同じように動作をします。ただし 接続する際には常にプロクシ経由となります。

require 'net/http'

proxy_addr = 'your.proxy.host'
proxy_port = 8080
        :
Net::HTTP::Proxy(proxy_addr, proxy_port).start('www.example.com') {|http|
  # always connect to your.proxy.addr:8080
        :
}

また Net::HTTP.Proxy は第一引数が nil だと Net::HTTP 自身を返すので 上のコードのように書いておけばプロクシなしの場合にも対応できます。

Net::HTTP.Proxy にはユーザ名とパスワードを取る オプション引数があり、以下のようにして プロクシの認証をすることができます。

proxy_host = 'your.proxy.host'
proxy_port = 8080
uri = URI.parse(ENV['http_proxy'])
proxy_user, proxy_pass = uri.userinfo.split(/:/) if uri.userinfo
Net::HTTP::Proxy(proxy_host, proxy_port,
                 proxy_user, proxy_pass).start('www.example.com') {|http|
  # always connect to your.proxy.addr:8080 using specified username and password
        :
}

このライブラリは環境変数 HTTP_PROXY を一切考慮しないこと に注意してください。プロクシを使いたい場合は上の例のように 明示的に取り扱わなければなりません。

リダイレクトに対応する

以下の例の fetch はリダイレクトに対応しています。 limit 回数以上リダイレクトしたらエラーにします。

require 'net/http'
require 'uri'

def fetch(uri_str, limit = 10)
  # You should choose better exception.
  raise ArgumentError, 'HTTP redirect too deep' if limit == 0

  response = Net::HTTP.get_response(URI.parse(uri_str))
  case response
  when Net::HTTPSuccess
    response
  when Net::HTTPRedirection
    fetch(response['location'], limit - 1)
  else
    response.value
  end
end

print fetch('http://www.example.org')

より詳しくは Net::HTTPResponseNet::HTTPSuccessNet::HTTPRedirection を参照してください。

Basic 認証

require 'net/http'

Net::HTTP.start('www.example.com') {|http|
  req = Net::HTTP::Get.new('/secret-page.html')
  req.basic_auth 'account', 'password'
  response = http.request(req)
  print response.body
}

フォームの値の区切り文字について

POSTで application/x-www-form-urlencoded として複数のフォームの値を送る場合、 現在広く行なわれているのは、 name0=value0&name1=value1 のようにアンパサンド (`&') で区切るやりかたです。 この方法は、[RFC1866] Hypertext Markup Language - 2.0 で初めて公式に登場し、 HTML 4.01 Specification の 17.13.4 Form content types でもそのように書かれています。

ところが、同じ HTML 4.01 Specification の B.2.2 Ampersands in URI attribute values では、 この `&' がSGMLの文字実体参照で用いられることが指摘されており、 CGIやサーバの実装者に対し `&' の代わりに セミコロン `;' をサポートすることを奨めています。

しかし、実際には `;' を解釈しないCGIやサーバもまだまだ見受けられるため このリファレンスマニュアルでは例として `&' を用いました。

なお Ruby 標準の cgi ライブラリでは '&' と ';' の両方サポートしていますので、 cgi ライブラリを使って CGI スクリプトを書く場合はこれらの違いを気にする 必要はありません。

クラス

class HTTPSession

Alias of Net::HTTP

class Net::HTTP

HTTP のクライアントのためのクラスです。

class Net::HTTPGenericRequest

Net::HTTPRequest のスーパークラスです。 このクラスは直接は使わないでください。

  class Net::HTTPRequest

HTTP リクエストを抽象化するクラスです。

   class Net::HTTP::Copy

HTTP の COPY リクエストを表すクラスです。

   class Net::HTTP::Delete

HTTP の DELETE リクエストを表すクラスです。

   class Net::HTTP::Get

HTTP の GET リクエストを表すクラスです。

   class Net::HTTP::Head

HTTP の HEAD リクエストを表すクラスです。

   class Net::HTTP::Lock

HTTP の LOCK リクエストを表すクラスです。

   class Net::HTTP::Mkcol

HTTP の MKCOL リクエストを表すクラスです。

   class Net::HTTP::Move

HTTP の MOVE リクエストを表すクラスです。

   class Net::HTTP::Options

HTTP の OPTIONS リクエストを表すクラスです。

   class Net::HTTP::Post

HTTP の POST リクエストを表すクラスです。

   class Net::HTTP::Propfind

HTTP の PROPFIND リクエストを表すクラスです。

   class Net::HTTP::Proppatch

HTTP の PROPPATCH リクエストを表すクラスです。

   class Net::HTTP::Put

HTTP の PUT リクエストを表すクラスです。

   class Net::HTTP::Trace

HTTP の TRACE リクエストを表すクラスです。

   class Net::HTTP::Unlock

HTTP の UNLOCK リクエストを表すクラスです。

class Net::HTTPResponse

HTTP レスポンスを表現するクラスです。 Net::HTTP クラスは実際には HTTPResponse のサブクラスを返します。

  class Net::HTTPClientError

HTTP レスポンス 4xx (Client Error) を表現するクラスです。

   class Net::HTTPBadRequest

HTTP レスポンス 400 (Bad Request) を表現するクラスです。

   class Net::HTTPConflict

HTTP レスポンス 409 (Conflict) を表現するクラスです。

   class Net::HTTPExpectationFailed

HTTP レスポンス 417 (Expectation Failed) を表現するクラスです。

   class Net::HTTPForbidden

HTTP レスポンス 403 (Forbidden) を表現するクラスです。

   class Net::HTTPGone

HTTP レスポンス 410 (Gone) を表現するクラスです。

   class Net::HTTPLengthRequired

HTTP レスポンス 411 (Length Required) を表現するクラスです。

   class Net::HTTPMethodNotAllowed

HTTP レスポンス 405 (Method Not Allowed) を表現するクラスです。

   class Net::HTTPNotAcceptable

HTTP レスポンス 406 (Not Acceptable) を表現するクラスです。

   class Net::HTTPNotFound

HTTP レスポンス 404 (Not Found) を表現するクラスです。

   class Net::HTTPPaymentRequired

HTTP レスポンス 402 (Payment Required) を表現するクラスです。

   class Net::HTTPPreconditionFailed

HTTP レスポンス 412 (Precondition Failed) を表現するクラスです。

   class Net::HTTPProxyAuthenticationRequired

HTTP レスポンス 407 (Proxy Authentication Required) を表現するクラスです。

   class Net::HTTPRequestEntityTooLarge

HTTP レスポンス 413 (Request Entity Too Large) を表現するクラスです。

   class Net::HTTPRequestTimeOut

HTTP レスポンス 408 (Request Time-out) を表現するクラスです。

   class Net::HTTPRequestURITooLarge

Alias of Net::HTTPRequestURITooLong

   class Net::HTTPRequestURITooLong

HTTP レスポンス 414 (Request-URI Too Large) を表現するクラスです。

   class Net::HTTPRequestedRangeNotSatisfiable

HTTP レスポンス 416 (Requested range not satisfiable) を表現するクラスです。

   class Net::HTTPUnauthorized

HTTP レスポンス 401 (Unauthorized) を表現するクラスです。

   class Net::HTTPUnsupportedMediaType

HTTP レスポンス 415 (Unsupported Media Type) を表現するクラスです。

  class Net::HTTPInformation

HTTP レスポンス 1xx (Informational) を表現するクラスです。

   class Net::HTTPContinue

HTTP レスポンス 100 (Continue) を表現するクラスです。

   class Net::HTTPSwitchProtocol

HTTP レスポンス 101 (Switching Protocols) を表現するクラスです。

  class Net::HTTPRedirection

HTTP レスポンス 3xx (Redirection) を表現するクラスです。

   class Net::HTTPFound

HTTP レスポンス 302 (Found) を表現するクラスです。 詳しくは [RFC2616] を見てください。

   class Net::HTTPMovedPermanently

HTTP レスポンス 301 (Moved Permanently) を表現するクラスです。

   class Net::HTTPMovedTemporarily

Alias of Net::HTTPFound

   class Net::HTTPMultipleChoice

HTTP レスポンス 300 (Multiple Choices) を表現するクラスです。

   class Net::HTTPNotModified

HTTP レスポンス 304 (Not Modified) を表現するクラスです。

   class Net::HTTPSeeOther

HTTP レスポンス 303 (See Other) を表現するクラスです。

   class Net::HTTPTemporaryRedirect

HTTP レスポンス 307 (Temporary Redirect) を表現するクラスです。

   class Net::HTTPUseProxy

HTTP レスポンス 305 (Use Proxy) を表現するクラスです。

  class Net::HTTPServerError

HTTP レスポンス 2xx (Server Error) を表現するクラスです。

   class Net::HTTPBadGateway

HTTP レスポンス 502 (Bad Gateway) を表現するクラスです。

   class Net::HTTPGatewayTimeOut

HTTP レスポンス 504 (Gateway Time-out) を表現するクラスです。

   class Net::HTTPInternalServerError

HTTP レスポンス 500 (Internal Server Error) を表現するクラスです。

   class Net::HTTPNotImplemented

HTTP レスポンス 501 (Not Implemented) を表現するクラスです。

   class Net::HTTPServiceUnavailable

HTTP レスポンス 503 (Service Unavailable) を表現するクラスです。

   class Net::HTTPVersionNotSupported

HTTP レスポンス 505 (HTTP Version not supported) を表現するクラスです。

  class Net::HTTPSuccess

HTTP レスポンス 2xx (Success) を表現するクラスです。

   class Net::HTTPAccepted

HTTP レスポンス 202 (Accepted) を表現するクラスです。

   class Net::HTTPCreated

HTTP レスポンス 201 (Created) を表現するクラスです。

   class Net::HTTPNoContent

HTTP レスポンス 204 (No Content) を表現するクラスです。

   class Net::HTTPNonAuthoritativeInformation

HTTP レスポンス 203 (Non-Authoritative Information) を表現するクラスです。

   class Net::HTTPOK

HTTP レスポンス 200 (OK) を表現するクラスです。

   class Net::HTTPPartialContent

HTTP レスポンス 206 (Partial Content) を表現するクラスです。

   class Net::HTTPResetContent

HTTP レスポンス 205 (Reset Content) を表現するクラスです。

  class Net::HTTPUnknownResponse

このライブラリが知らないレスポンスを表現するクラスです。

モジュール

module Net::HTTPExceptions

HTTP 例外クラスです。

module Net::HTTPHeader

HTTP ヘッダのためのモジュールです。

例外クラス

class Net::HTTPBadResponse

HTTP のレスポンスが不正であった場合に発生する例外です。

class Net::HTTPHeaderSyntaxError

HTTP ヘッダの内容が不正である場合に発生する例外です。

class Net::HTTPError

HTTP ステータスコード 1xx を受け取ったという例外です。 または、ステータスコードが未知のものである場合も これに対応します。

class Net::HTTPFatalError

HTTP ステータスコード 4xx を受け取ったという例外です。

class Net::HTTPRetriableError

HTTP ステータスコード 3xx を受け取ったという例外です。

class Net::HTTPServerException

HTTP ステータスコード 5xx を受け取ったという例外です。

library net/http