Class Net::HTTP
In: lib/net/https.rb
lib/net/http.rb
Parent: Object

What Is This Library?

This library provides your program functions to access WWW documents via HTTP, Hyper Text Transfer Protocol version 1.1. For details of HTTP, refer [RFC2616] (www.ietf.org/rfc/rfc2616.txt).

Examples

Getting Document From WWW Server

Example 1: Simple GET+print

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

Example 2: Simple GET+print by URL

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

Example 3: More generic GET+print

    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

Example 4: More generic GET+print

    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

Posting Form Data

    require 'net/http'
    require 'uri'

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

    #2: POST with basic authentication
    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: Detailed control
    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.error!
    end

Accessing via Proxy

Net::HTTP.Proxy creates http proxy class. It has same methods of Net::HTTP but its instances always connect to proxy, instead of given host.

    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
            :
    }

Since Net::HTTP.Proxy returns Net::HTTP itself when proxy_addr is nil, there‘s no need to change code if there‘s proxy or not.

There are two additional parameters in Net::HTTP.Proxy which allow to specify proxy user name and password:

    Net::HTTP::Proxy(proxy_addr, proxy_port, proxy_user = nil, proxy_pass = nil)

You may use them to work with authorization-enabled proxies:

    require 'net/http'
    require 'uri'

    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
            :
    }

Note that net/http never rely on HTTP_PROXY environment variable. If you want to use proxy, set it explicitly.

Following Redirection

    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     then response
      when Net::HTTPRedirection then fetch(response['location'], limit - 1)
      else
        response.error!
      end
    end

    print fetch('http://www.ruby-lang.org')

Net::HTTPSuccess and Net::HTTPRedirection is a HTTPResponse class. All HTTPResponse objects belong to its own response class which indicate HTTP result status. For details of response classes, see section "HTTP Response Classes".

Basic Authentication

    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
    }

HTTP Request Classes

Here is HTTP request class hierarchy.

  Net::HTTPRequest
      Net::HTTP::Get
      Net::HTTP::Head
      Net::HTTP::Post
      Net::HTTP::Put
      Net::HTTP::Proppatch
      Net::HTTP::Lock
      Net::HTTP::Unlock
      Net::HTTP::Options
      Net::HTTP::Propfind
      Net::HTTP::Delete
      Net::HTTP::Move
      Net::HTTP::Copy
      Net::HTTP::Mkcol
      Net::HTTP::Trace

HTTP Response Classes

Here is HTTP response class hierarchy. All classes are defined in Net module.

  HTTPResponse
      HTTPUnknownResponse
      HTTPInformation                    # 1xx
          HTTPContinue                       # 100
          HTTPSwitchProtocl                  # 101
      HTTPSuccess                        # 2xx
          HTTPOK                             # 200
          HTTPCreated                        # 201
          HTTPAccepted                       # 202
          HTTPNonAuthoritativeInformation    # 203
          HTTPNoContent                      # 204
          HTTPResetContent                   # 205
          HTTPPartialContent                 # 206
      HTTPRedirection                    # 3xx
          HTTPMultipleChoice                 # 300
          HTTPMovedPermanently               # 301
          HTTPFound                          # 302
          HTTPSeeOther                       # 303
          HTTPNotModified                    # 304
          HTTPUseProxy                       # 305
          HTTPTemporaryRedirect              # 307
      HTTPClientError                    # 4xx
          HTTPBadRequest                     # 400
          HTTPUnauthorized                   # 401
          HTTPPaymentRequired                # 402
          HTTPForbidden                      # 403
          HTTPNotFound                       # 404
          HTTPMethodNotAllowed               # 405
          HTTPNotAcceptable                  # 406
          HTTPProxyAuthenticationRequired    # 407
          HTTPRequestTimeOut                 # 408
          HTTPConflict                       # 409
          HTTPGone                           # 410
          HTTPLengthRequired                 # 411
          HTTPPreconditionFailed             # 412
          HTTPRequestEntityTooLarge          # 413
          HTTPRequestURITooLong              # 414
          HTTPUnsupportedMediaType           # 415
          HTTPRequestedRangeNotSatisfiable   # 416
          HTTPExpectationFailed              # 417
      HTTPServerError                    # 5xx
          HTTPInternalServerError            # 500
          HTTPNotImplemented                 # 501
          HTTPBadGateway                     # 502
          HTTPServiceUnavailable             # 503
          HTTPGatewayTimeOut                 # 504
          HTTPVersionNotSupported            # 505

Switching Net::HTTP versions

You can use net/http.rb 1.1 features (bundled with Ruby 1.6) by calling HTTP.version_1_1. Calling Net::HTTP.version_1_2 allows you to use 1.2 features again.

    # example
    Net::HTTP.start {|http1| ...(http1 has 1.2 features)... }

    Net::HTTP.version_1_1
    Net::HTTP.start {|http2| ...(http2 has 1.1 features)... }

    Net::HTTP.version_1_2
    Net::HTTP.start {|http3| ...(http3 has 1.2 features)... }

This function is NOT thread-safe.

Methods

Classes and Modules

Class Net::HTTP::Copy
Class Net::HTTP::Delete
Class Net::HTTP::Get
Class Net::HTTP::Head
Class Net::HTTP::Lock
Class Net::HTTP::Mkcol
Class Net::HTTP::Move
Class Net::HTTP::Options
Class Net::HTTP::Post
Class Net::HTTP::Propfind
Class Net::HTTP::Proppatch
Class Net::HTTP::Put
Class Net::HTTP::Trace
Class Net::HTTP::Unlock

External Aliases

version_1_1? -> is_version_1_1?
version_1_2? -> is_version_1_2?
new -> newobj
request_put -> put2

Attributes

address  [R]  The host name to connect to.
close_on_empty_response  [RW] 
enable_post_connection_check  [RW]  specify enabling SSL server certificate and hostname checking.
open_timeout  [RW]  Seconds to wait until connection is opened. If the HTTP object cannot open a connection in this many seconds, it raises a TimeoutError exception.
port  [R]  The port number to connect to.
proxy_address  [R] 
proxy_pass  [R] 
proxy_port  [R] 
proxy_user  [R] 
read_timeout  [R]  Seconds to wait until reading one block (by one read(2) call). If the HTTP object cannot open a connection in this many seconds, it raises a TimeoutError exception.

Public Class methods

Creates an HTTP proxy class. Arguments are address/port of proxy host and username/password if authorization on proxy server is required. You can replace the HTTP class with created proxy class.

If ADDRESS is nil, this method returns self (Net::HTTP).

    # Example
    proxy_class = Net::HTTP::Proxy('proxy.example.com', 8080)
                    :
    proxy_class.start('www.ruby-lang.org') {|http|
      # connecting proxy.foo.org:8080
                    :
    }

[Source]

     # File lib/net/http.rb, line 650
650:     def HTTP.Proxy(p_addr, p_port = nil, p_user = nil, p_pass = nil)
651:       return self unless p_addr
652:       delta = ProxyDelta
653:       proxyclass = Class.new(self)
654:       proxyclass.module_eval {
655:         include delta
656:         # with proxy
657:         @is_proxy_class = true
658:         @proxy_address = p_addr
659:         @proxy_port    = p_port || default_port()
660:         @proxy_user    = p_user
661:         @proxy_pass    = p_pass
662:       }
663:       proxyclass
664:     end

The default port to use for HTTP requests; defaults to 80.

[Source]

     # File lib/net/http.rb, line 414
414:     def HTTP.default_port
415:       http_default_port()
416:     end

Send a GET request to the target and return the response as a string. The target can either be specified as (uri), or as (host, path, port = 80); so:

   print Net::HTTP.get(URI.parse('http://www.example.com/index.html'))

or:

   print Net::HTTP.get('www.example.com', '/index.html')

[Source]

     # File lib/net/http.rb, line 355
355:     def HTTP.get(uri_or_host, path = nil, port = nil)
356:       get_response(uri_or_host, path, port).body
357:     end

Get body from target and output it to +$stdout+. The target can either be specified as (uri), or as (host, path, port = 80); so:

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

or:

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

[Source]

     # File lib/net/http.rb, line 336
336:     def HTTP.get_print(uri_or_host, path = nil, port = nil)
337:       get_response(uri_or_host, path, port) {|res|
338:         res.read_body do |chunk|
339:           $stdout.print chunk
340:         end
341:       }
342:       nil
343:     end

Send a GET request to the target and return the response as a Net::HTTPResponse object. The target can either be specified as (uri), or as (host, path, port = 80); so:

   res = Net::HTTP.get_response(URI.parse('http://www.example.com/index.html'))
   print res.body

or:

   res = Net::HTTP.get_response('www.example.com', '/index.html')
   print res.body

[Source]

     # File lib/net/http.rb, line 371
371:     def HTTP.get_response(uri_or_host, path = nil, port = nil, &block)
372:       if path
373:         host = uri_or_host
374:         new(host, port || HTTP.default_port).start {|http|
375:           return http.request_get(path, &block)
376:         }
377:       else
378:         uri = uri_or_host
379:         new(uri.host, uri.port).start {|http|
380:           return http.request_get(uri.request_uri, &block)
381:         }
382:       end
383:     end

The default port to use for HTTP requests; defaults to 80.

[Source]

     # File lib/net/http.rb, line 419
419:     def HTTP.http_default_port
420:       80
421:     end

The default port to use for HTTPS requests; defaults to 443.

[Source]

     # File lib/net/http.rb, line 424
424:     def HTTP.https_default_port
425:       443
426:     end

Creates a new Net::HTTP object. If proxy_addr is given, creates an Net::HTTP object with proxy support. This method does not open the TCP connection.

[Source]

     # File lib/net/http.rb, line 450
450:     def HTTP.new(address, port = nil, p_addr = nil, p_port = nil, p_user = nil, p_pass = nil)
451:       h = Proxy(p_addr, p_port, p_user, p_pass).newobj(address, port)
452:       h.instance_eval {
453:         @newimpl = ::Net::HTTP.version_1_2?
454:       }
455:       h
456:     end

Creates a new Net::HTTP object for the specified address. This method does not open the TCP connection.

[Source]

     # File lib/net/http.rb, line 460
460:     def initialize(address, port = nil)
461:       @address = address
462:       @port    = (port || HTTP.default_port)
463:       @curr_http_version = HTTPVersion
464:       @seems_1_0_server = false
465:       @close_on_empty_response = false
466:       @socket  = nil
467:       @started = false
468:       @open_timeout = nil
469:       @read_timeout = 60
470:       @debug_output = nil
471:       @use_ssl = false
472:       @ssl_context = nil
473:       @enable_post_connection_check = false
474:     end

Posts HTML form data to the URL. Form data must be represented as a Hash of String to String, e.g:

  { "cmd" => "search", "q" => "ruby", "max" => "50" }

This method also does Basic Authentication iff URL.user exists.

Example:

  require 'net/http'
  require 'uri'

  HTTP.post_form URI.parse('http://www.example.com/search.cgi'),
                 { "q" => "ruby", "max" => "50" }

[Source]

     # File lib/net/http.rb, line 400
400:     def HTTP.post_form(url, params)
401:       req = Post.new(url.path)
402:       req.form_data = params
403:       req.basic_auth url.user, url.password if url.user
404:       new(url.host, url.port).start {|http|
405:         http.request(req)
406:       }
407:     end

returns true if self is a class which was created by HTTP::Proxy.

[Source]

     # File lib/net/http.rb, line 668
668:       def proxy_class?
669:         @is_proxy_class
670:       end

[Source]

     # File lib/net/https.rb, line 129
129:     def self.ssl_context_accessor(name)
130:       module_eval("def \#{name}\nreturn nil unless @ssl_context\n@ssl_context.\#{name}\nend\n\ndef \#{name}=(val)\n@ssl_context ||= OpenSSL::SSL::SSLContext.new\n@ssl_context.\#{name} = val\nend\n", __FILE__, __LINE__ + 1)
131:     end

creates a new Net::HTTP object and opens its TCP connection and HTTP session. If the optional block is given, the newly created Net::HTTP object is passed to it and closed when the block finishes. In this case, the return value of this method is the return value of the block. If no block is given, the return value of this method is the newly created Net::HTTP object itself, and the caller is responsible for closing it upon completion.

[Source]

     # File lib/net/http.rb, line 439
439:     def HTTP.start(address, port = nil, p_addr = nil, p_port = nil, p_user = nil, p_pass = nil, &block) # :yield: +http+
440:       new(address, port, p_addr, p_port, p_user, p_pass).start(&block)
441:     end

Turns on net/http 1.1 (ruby 1.6) features. Defaults to OFF in ruby 1.8.

[Source]

     # File lib/net/http.rb, line 300
300:     def HTTP.version_1_1
301:       @newimpl = false
302:     end

true if net/http is in version 1.1 compatible mode. Defaults to true.

[Source]

     # File lib/net/http.rb, line 312
312:     def HTTP.version_1_1?
313:       not @newimpl
314:     end

Turns on net/http 1.2 (ruby 1.8) features. Defaults to ON in ruby 1.8.

I strongly recommend to call this method always.

  require 'net/http'
  Net::HTTP.version_1_2

[Source]

     # File lib/net/http.rb, line 294
294:     def HTTP.version_1_2
295:       @newimpl = true
296:     end

true if net/http is in version 1.2 mode. Defaults to true.

[Source]

     # File lib/net/http.rb, line 306
306:     def HTTP.version_1_2?
307:       @newimpl
308:     end

Public Instance methods

active?()

Alias for started?

Sends a COPY request to the path and gets a response, as an HTTPResponse object.

[Source]

     # File lib/net/http.rb, line 915
915:     def copy(path, initheader = nil)
916:       request(Copy.new(path, initheader))
917:     end

Sends a DELETE request to the path and gets a response, as an HTTPResponse object.

[Source]

     # File lib/net/http.rb, line 903
903:     def delete(path, initheader = {'Depth' => 'Infinity'})
904:       request(Delete.new(path, initheader))
905:     end

Finishes HTTP session and closes TCP connection. Raises IOError if not started.

[Source]

     # File lib/net/http.rb, line 610
610:     def finish
611:       raise IOError, 'HTTP session not yet started' unless started?
612:       do_finish
613:     end

Gets data from path on the connected-to host. header must be a Hash like { ‘Accept’ => ’*/*’, … }.

In version 1.1 (ruby 1.6), this method returns a pair of objects, a Net::HTTPResponse object and the entity body string. In version 1.2 (ruby 1.8), this method returns a Net::HTTPResponse object.

If called with a block, yields each fragment of the entity body in turn as a string as it is read from the socket. Note that in this case, the returned response object will not contain a (meaningful) body.

dest argument is obsolete. It still works but you must not use it.

In version 1.1, this method might raise an exception for 3xx (redirect). In this case you can get a HTTPResponse object by "anException.response".

In version 1.2, this method never raises exception.

    # version 1.1 (bundled with Ruby 1.6)
    response, body = http.get('/index.html')

    # version 1.2 (bundled with Ruby 1.8 or later)
    response = http.get('/index.html')

    # using block
    File.open('result.txt', 'w') {|f|
      http.get('/~foo/') do |str|
        f.write str
      end
    }

[Source]

     # File lib/net/http.rb, line 779
779:     def get(path, initheader = nil, dest = nil, &block) # :yield: +body_segment+
780:       res = nil
781:       request(Get.new(path, initheader)) {|r|
782:         r.read_body dest, &block
783:         res = r
784:       }
785:       unless @newimpl
786:         res.value
787:         return res, res.body
788:       end
789: 
790:       res
791:     end
get2(path, initheader = nil)

Alias for request_get

Gets only the header from path on the connected-to host. header is a Hash like { ‘Accept’ => ’*/*’, … }.

This method returns a Net::HTTPResponse object.

In version 1.1, this method might raise an exception for 3xx (redirect). On the case you can get a HTTPResponse object by "anException.response". In version 1.2, this method never raises an exception.

    response = nil
    Net::HTTP.start('some.www.server', 80) {|http|
      response = http.head('/index.html')
    }
    p response['content-type']

[Source]

     # File lib/net/http.rb, line 809
809:     def head(path, initheader = nil) 
810:       res = request(Head.new(path, initheader))
811:       res.value unless @newimpl
812:       res
813:     end
head2(path, initheader = nil, &block)

Alias for request_head

[Source]

     # File lib/net/http.rb, line 476
476:     def inspect
477:       "#<#{self.class} #{@address}:#{@port} open=#{started?}>"
478:     end

Sends a LOCK request to the path and gets a response, as an HTTPResponse object.

[Source]

     # File lib/net/http.rb, line 879
879:     def lock(path, body, initheader = nil)
880:       request(Lock.new(path, initheader), body)
881:     end

Sends a MKCOL request to the path and gets a response, as an HTTPResponse object.

[Source]

     # File lib/net/http.rb, line 921
921:     def mkcol(path, body = nil, initheader = nil)
922:       request(Mkcol.new(path, initheader), body)
923:     end

Sends a MOVE request to the path and gets a response, as an HTTPResponse object.

[Source]

     # File lib/net/http.rb, line 909
909:     def move(path, initheader = nil)
910:       request(Move.new(path, initheader))
911:     end

Sends a OPTIONS request to the path and gets a response, as an HTTPResponse object.

[Source]

     # File lib/net/http.rb, line 891
891:     def options(path, initheader = nil)
892:       request(Options.new(path, initheader))
893:     end

[Source]

     # File lib/net/https.rb, line 168
168:     def peer_cert
169:       return nil if not use_ssl? or not @socket
170:       @socket.io.peer_cert
171:     end

Posts data (must be a String) to path. header must be a Hash like { ‘Accept’ => ’*/*’, … }.

In version 1.1 (ruby 1.6), this method returns a pair of objects, a Net::HTTPResponse object and an entity body string. In version 1.2 (ruby 1.8), this method returns a Net::HTTPResponse object.

If called with a block, yields each fragment of the entity body in turn as a string as it are read from the socket. Note that in this case, the returned response object will not contain a (meaningful) body.

dest argument is obsolete. It still works but you must not use it.

In version 1.1, this method might raise an exception for 3xx (redirect). In this case you can get an HTTPResponse object by "anException.response". In version 1.2, this method never raises exception.

    # version 1.1
    response, body = http.post('/cgi-bin/search.rb', 'query=foo')

    # version 1.2
    response = http.post('/cgi-bin/search.rb', 'query=foo')

    # using block
    File.open('result.txt', 'w') {|f|
      http.post('/cgi-bin/search.rb', 'query=foo') do |str|
        f.write str
      end
    }

You should set Content-Type: header field for POST. If no Content-Type: field given, this method uses "application/x-www-form-urlencoded" by default.

[Source]

     # File lib/net/http.rb, line 852
852:     def post(path, data, initheader = nil, dest = nil, &block) # :yield: +body_segment+
853:       res = nil
854:       request(Post.new(path, initheader), data) {|r|
855:         r.read_body dest, &block
856:         res = r
857:       }
858:       unless @newimpl
859:         res.value
860:         return res, res.body
861:       end
862:       res
863:     end
post2(path, data, initheader = nil)

Alias for request_post

Sends a PROPFIND request to the path and gets a response, as an HTTPResponse object.

[Source]

     # File lib/net/http.rb, line 897
897:     def propfind(path, body = nil, initheader = {'Depth' => '0'})
898:       request(Propfind.new(path, initheader), body)
899:     end

Sends a PROPPATCH request to the path and gets a response, as an HTTPResponse object.

[Source]

     # File lib/net/http.rb, line 873
873:     def proppatch(path, body, initheader = nil)
874:       request(Proppatch.new(path, initheader), body)
875:     end

True if self is a HTTP proxy class.

[Source]

     # File lib/net/http.rb, line 679
679:     def proxy?
680:       self.class.proxy_class?
681:     end

Address of proxy host. If self does not use a proxy, nil.

[Source]

     # File lib/net/http.rb, line 684
684:     def proxy_address
685:       self.class.proxy_address
686:     end

User password for accessing proxy. If self does not use a proxy, nil.

[Source]

     # File lib/net/http.rb, line 699
699:     def proxy_pass
700:       self.class.proxy_pass
701:     end

Port number of proxy host. If self does not use a proxy, nil.

[Source]

     # File lib/net/http.rb, line 689
689:     def proxy_port
690:       self.class.proxy_port
691:     end

User name for accessing proxy. If self does not use a proxy, nil.

[Source]

     # File lib/net/http.rb, line 694
694:     def proxy_user
695:       self.class.proxy_user
696:     end
proxyaddr()

Alias for proxy_address

proxyport()

Alias for proxy_port

Setter for the read_timeout attribute.

[Source]

     # File lib/net/http.rb, line 511
511:     def read_timeout=(sec)
512:       @socket.read_timeout = sec if @socket
513:       @read_timeout = sec
514:     end

Sends an HTTPRequest object REQUEST to the HTTP server. This method also sends DATA string if REQUEST is a post/put request. Giving DATA for get/head request causes ArgumentError.

When called with a block, yields an HTTPResponse object. The body of this response will not have been read yet; the caller can process it using HTTPResponse#read_body, if desired.

Returns a HTTPResponse object.

This method never raises Net::* exceptions.

[Source]

      # File lib/net/http.rb, line 1042
1042:     def request(req, body = nil, &block)  # :yield: +response+
1043:       unless started?
1044:         start {
1045:           req['connection'] ||= 'close'
1046:           return request(req, body, &block)
1047:         }
1048:       end
1049:       if proxy_user()
1050:         unless use_ssl?
1051:           req.proxy_basic_auth proxy_user(), proxy_pass()
1052:         end
1053:       end
1054: 
1055:       req.set_body_internal body
1056:       begin_transport req
1057:         req.exec @socket, @curr_http_version, edit_path(req.path)
1058:         begin
1059:           res = HTTPResponse.read_new(@socket)
1060:         end while res.kind_of?(HTTPContinue)
1061:         res.reading_body(@socket, req.response_body_permitted?) {
1062:           yield res if block_given?
1063:         }
1064:       end_transport req, res
1065: 
1066:       res
1067:     end

Sends a GET request to the path and gets a response, as an HTTPResponse object.

When called with a block, yields an HTTPResponse object. The body of this response will not have been read yet; the caller can process it using HTTPResponse#read_body, if desired.

Returns the response.

This method never raises Net::* exceptions.

    response = http.request_get('/index.html')
    # The entity body is already read here.
    p response['content-type']
    puts response.body

    # using block
    http.request_get('/index.html') {|response|
      p response['content-type']
      response.read_body do |str|   # read body now
        print str
      end
    }

[Source]

     # File lib/net/http.rb, line 956
956:     def request_get(path, initheader = nil, &block) # :yield: +response+
957:       request(Get.new(path, initheader), &block)
958:     end

Sends a HEAD request to the path and gets a response, as an HTTPResponse object.

Returns the response.

This method never raises Net::* exceptions.

    response = http.request_head('/index.html')
    p response['content-type']

[Source]

     # File lib/net/http.rb, line 970
970:     def request_head(path, initheader = nil, &block)
971:       request(Head.new(path, initheader), &block)
972:     end

Sends a POST request to the path and gets a response, as an HTTPResponse object.

When called with a block, yields an HTTPResponse object. The body of this response will not have been read yet; the caller can process it using HTTPResponse#read_body, if desired.

Returns the response.

This method never raises Net::* exceptions.

    # example
    response = http.request_post('/cgi-bin/nice.rb', 'datadatadata...')
    p response.status
    puts response.body          # body is already read

    # using block
    http.request_post('/cgi-bin/nice.rb', 'datadatadata...') {|response|
      p response.status
      p response['content-type']
      response.read_body do |str|   # read body now
        print str
      end
    }

[Source]

      # File lib/net/http.rb, line 1000
1000:     def request_post(path, data, initheader = nil, &block) # :yield: +response+
1001:       request Post.new(path, initheader), data, &block
1002:     end

Sends an HTTP request to the HTTP server. This method also sends DATA string if DATA is given.

Returns a HTTPResponse object.

This method never raises Net::* exceptions.

   response = http.send_request('GET', '/index.html')
   puts response.body

[Source]

      # File lib/net/http.rb, line 1024
1024:     def send_request(name, path, data = nil, header = nil)
1025:       r = HTTPGenericRequest.new(name,(data ? true : false),true,path,header)
1026:       request r, data
1027:     end

WARNING This method causes serious security hole. Never use this method in production code.

Set an output stream for debugging.

  http = Net::HTTP.new
  http.set_debug_output $stderr
  http.start { .... }

[Source]

     # File lib/net/http.rb, line 489
489:     def set_debug_output(output)
490:       warn 'Net::HTTP#set_debug_output called after HTTP started' if started?
491:       @debug_output = output
492:     end

[Source]

     # File lib/net/https.rb, line 153
153:     def ssl_timeout
154:       return nil unless @ssl_context
155:       @ssl_context.timeout
156:     end

[Source]

     # File lib/net/https.rb, line 158
158:     def ssl_timeout=(sec)
159:       raise ArgumentError, 'Net::HTTP#ssl_timeout= called but use_ssl=false' \
160:           unless use_ssl?
161:       @ssl_context ||= OpenSSL::SSL::SSLContext.new
162:       @ssl_context.timeout = sec
163:     end

Opens TCP connection and HTTP session.

When this method is called with block, gives a HTTP object to the block and closes the TCP connection / HTTP session after the block executed.

When called with a block, returns the return value of the block; otherwise, returns self.

[Source]

     # File lib/net/http.rb, line 542
542:     def start  # :yield: http
543:       raise IOError, 'HTTP session already opened' if @started
544:       if block_given?
545:         begin
546:           do_start
547:           return yield(self)
548:         ensure
549:           do_finish
550:         end
551:       end
552:       do_start
553:       self
554:     end

returns true if the HTTP session is started.

[Source]

     # File lib/net/http.rb, line 517
517:     def started?
518:       @started
519:     end
timeout=(sec)

Alias for ssl_timeout=

Sends a TRACE request to the path and gets a response, as an HTTPResponse object.

[Source]

     # File lib/net/http.rb, line 927
927:     def trace(path, initheader = nil)
928:       request(Trace.new(path, initheader))
929:     end

Sends a UNLOCK request to the path and gets a response, as an HTTPResponse object.

[Source]

     # File lib/net/http.rb, line 885
885:     def unlock(path, body, initheader = nil)
886:       request(Unlock.new(path, initheader), body)
887:     end
use_ssl()

Alias for use_ssl?

Turn on/off SSL. This flag must be set before starting session. If you change use_ssl value after session started, a Net::HTTP object raises IOError.

[Source]

     # File lib/net/https.rb, line 119
119:     def use_ssl=(flag)
120:       flag = (flag ? true : false)
121:       raise IOError, "use_ssl value changed, but session already started" \
122:           if started? and @use_ssl != flag
123:       if flag and not @ssl_context
124:         @ssl_context = OpenSSL::SSL::SSLContext.new
125:       end
126:       @use_ssl = flag
127:     end

returns true if use SSL/TLS with HTTP.

[Source]

     # File lib/net/http.rb, line 526
526:     def use_ssl?
527:       false   # redefined in net/https
528:     end

[Source]

     # File lib/net/https.rb, line 108
108:     def use_ssl?
109:       @use_ssl
110:     end

Private Instance methods

[Source]

      # File lib/net/http.rb, line 1125
1125:     def D(msg)
1126:       return unless @debug_output
1127:       @debug_output << msg
1128:       @debug_output << "\n"
1129:     end

utils

[Source]

      # File lib/net/http.rb, line 1117
1117:     def addr_port
1118:       if use_ssl?
1119:         address() + (port == HTTP.https_default_port ? '' : ":#{port()}")
1120:       else
1121:         address() + (port == HTTP.http_default_port ? '' : ":#{port()}")
1122:       end
1123:     end

[Source]

      # File lib/net/http.rb, line 1071
1071:     def begin_transport(req)
1072:       if @socket.closed?
1073:         connect
1074:       end
1075:       if @seems_1_0_server
1076:         req['connection'] ||= 'close'
1077:       end
1078:       if not req.response_body_permitted? and @close_on_empty_response
1079:         req['connection'] ||= 'close'
1080:       end
1081:       req['host'] ||= addr_port()
1082:     end

without proxy

[Source]

     # File lib/net/http.rb, line 710
710:     def conn_address
711:       address()
712:     end

[Source]

     # File lib/net/http.rb, line 714
714:     def conn_port
715:       port()
716:     end

[Source]

     # File lib/net/http.rb, line 562
562:     def connect
563:       D "opening connection to #{conn_address()}..."
564:       s = timeout(@open_timeout) { TCPSocket.open(conn_address(), conn_port()) }
565:       D "opened"
566:       if use_ssl?
567:         unless @ssl_context.verify_mode
568:           warn "warning: peer certificate won't be verified in this SSL session"
569:           @ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE
570:         end
571:         s = OpenSSL::SSL::SSLSocket.new(s, @ssl_context)
572:         s.sync_close = true
573:       end
574:       @socket = BufferedIO.new(s)
575:       @socket.read_timeout = @read_timeout
576:       @socket.debug_output = @debug_output
577:       if use_ssl?
578:         if proxy?
579:           @socket.writeline sprintf('CONNECT %s:%s HTTP/%s',
580:                                     @address, @port, HTTPVersion)
581:           @socket.writeline "Host: #{@address}:#{@port}"
582:           if proxy_user
583:             credential = ["#{proxy_user}:#{proxy_pass}"].pack('m')
584:             credential.delete!("\r\n")
585:             @socket.writeline "Proxy-Authorization: Basic #{credential}"
586:           end
587:           @socket.writeline ''
588:           HTTPResponse.read_new(@socket).value
589:         end
590:         s.connect
591:         if @ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE
592:           begin
593:             s.post_connection_check(@address)
594:           rescue OpenSSL::SSL::SSLError => ex
595:             raise ex if @enable_post_connection_check
596:             warn ex.message
597:           end
598:         end
599:       end
600:       on_connect
601:     end

[Source]

     # File lib/net/http.rb, line 615
615:     def do_finish
616:       @started = false
617:       @socket.close if @socket and not @socket.closed?
618:       @socket = nil
619:     end

[Source]

     # File lib/net/http.rb, line 556
556:     def do_start
557:       connect
558:       @started = true
559:     end

[Source]

     # File lib/net/http.rb, line 718
718:     def edit_path(path)
719:       path
720:     end

[Source]

      # File lib/net/http.rb, line 1084
1084:     def end_transport(req, res)
1085:       @curr_http_version = res.http_version
1086:       if not res.body and @close_on_empty_response
1087:         D 'Conn close'
1088:         @socket.close
1089:       elsif keep_alive?(req, res)
1090:         D 'Conn keep-alive'
1091:         if @socket.closed?
1092:           D 'Conn (but seems 1.0 server)'
1093:           @seems_1_0_server = true
1094:         end
1095:       else
1096:         D 'Conn close'
1097:         @socket.close
1098:       end
1099:     end

[Source]

      # File lib/net/http.rb, line 1101
1101:     def keep_alive?(req, res)
1102:       return false if /close/i =~ req['connection'].to_s
1103:       return false if @seems_1_0_server
1104:       return true  if /keep-alive/i =~ res['connection'].to_s
1105:       return false if /close/i      =~ res['connection'].to_s
1106:       return true  if /keep-alive/i =~ res['proxy-connection'].to_s
1107:       return false if /close/i      =~ res['proxy-connection'].to_s
1108:       (@curr_http_version == '1.1')
1109:     end

[Source]

     # File lib/net/http.rb, line 604
604:     def on_connect
605:     end

[Validate]