Class: Net::HTTP::HTTP

Inherits:
Object
  • Object
show all
Defined in:
lib/net/http.rb

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.default_configurationObject

Allows to set the default configuration that will be used when creating a new connection.

Example:

Net::HTTP.default_configuration = {
read_timeout: 1,
write_timeout: 1
}
http = Net::HTTP.new(hostname)
http.open_timeout   # => 60
http.read_timeout   # => 1
http.write_timeout  # => 1


1142
1143
1144
# File 'lib/net/http.rb', line 1142

def default_configuration
  @default_configuration
end

.proxy_addressObject (readonly)

Returns the address of the proxy host, or nil if none; see Net::HTTP@Proxy+Server.



1832
1833
1834
# File 'lib/net/http.rb', line 1832

def proxy_address
  @proxy_address
end

.proxy_passObject (readonly)

Returns the password for accessing the proxy, or nil if none; see Net::HTTP@Proxy+Server.



1844
1845
1846
# File 'lib/net/http.rb', line 1844

def proxy_pass
  @proxy_pass
end

.proxy_portObject (readonly)

Returns the port number of the proxy host, or nil if none; see Net::HTTP@Proxy+Server.



1836
1837
1838
# File 'lib/net/http.rb', line 1836

def proxy_port
  @proxy_port
end

.proxy_use_sslObject (readonly)

Use SSL when talking to the proxy. If Net::HTTP does not use a proxy, nil.



1847
1848
1849
# File 'lib/net/http.rb', line 1847

def proxy_use_ssl
  @proxy_use_ssl
end

.proxy_userObject (readonly)

Returns the user name for accessing the proxy, or nil if none; see Net::HTTP@Proxy+Server.



1840
1841
1842
# File 'lib/net/http.rb', line 1840

def proxy_user
  @proxy_user
end

Class Method Details

.default_portObject

Returns integer 80, the default port to use for HTTP requests:

Net::HTTP.default_port # => 80


935
936
937
# File 'lib/net/http.rb', line 935

def HTTP.default_port
  http_default_port()
end

.get(uri_or_host, path_or_headers = nil, port = nil) ⇒ Object

:call-seq:

Net::HTTP.get(hostname, path, port = 80) -> body
Net::HTTP:get(uri, headers = {}, port = uri.port) -> body

Sends a GET request and returns the HTTP response body as a string.

With string arguments hostname and path:

hostname = 'jsonplaceholder.typicode.com'
path = '/todos/1'
puts Net::HTTP.get(hostname, path)

Output:

{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}

With URI object uri and optional hash argument headers:

uri = URI('https://jsonplaceholder.typicode.com/todos/1')
headers = {'Content-type' => 'application/json; charset=UTF-8'}
Net::HTTP.get(uri, headers)

Related:

  • Net::HTTP::Get: request class for HTTP method GET.
  • Net::HTTP#get: convenience method for HTTP method GET.


804
805
806
# File 'lib/net/http.rb', line 804

def HTTP.get(uri_or_host, path_or_headers = nil, port = nil)
  get_response(uri_or_host, path_or_headers, port).body
end

.get_print(uri_or_host, path_or_headers = nil, port = nil) ⇒ Object

:call-seq:

Net::HTTP.get_print(hostname, path, port = 80) -> nil
Net::HTTP:get_print(uri, headers = {}, port = uri.port) -> nil

Like Net::HTTP.get, but writes the returned body to $stdout; returns nil.



763
764
765
766
767
768
769
770
# File 'lib/net/http.rb', line 763

def HTTP.get_print(uri_or_host, path_or_headers = nil, port = nil)
  get_response(uri_or_host, path_or_headers, port) {|res|
    res.read_body do |chunk|
      $stdout.print chunk
    end
  }
  nil
end

.get_response(uri_or_host, path_or_headers = nil, port = nil, &block) ⇒ Object

:call-seq:

Net::HTTP.get_response(hostname, path, port = 80) -> http_response
Net::HTTP:get_response(uri, headers = {}, port = uri.port) -> http_response

Like Net::HTTP.get, but returns a Net::HTTPResponse object instead of the body string.



814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
# File 'lib/net/http.rb', line 814

def HTTP.get_response(uri_or_host, path_or_headers = nil, port = nil, &block)
  if path_or_headers && !path_or_headers.is_a?(Hash)
    host = uri_or_host
    path = path_or_headers
    new(host, port || HTTP.default_port).start {|http|
      return http.request_get(path, &block)
    }
  else
    uri = uri_or_host
    headers = path_or_headers
    start(uri.hostname, uri.port,
          :use_ssl => uri.scheme == 'https') {|http|
      return http.request_get(uri, headers, &block)
    }
  end
end

.http_default_portObject

Returns integer 80, the default port to use for HTTP requests:

Net::HTTP.http_default_port # => 80


943
944
945
# File 'lib/net/http.rb', line 943

def HTTP.http_default_port
  80
end

.https_default_portObject

Returns integer 443, the default port to use for HTTPS requests:

Net::HTTP.https_default_port # => 443


951
952
953
# File 'lib/net/http.rb', line 951

def HTTP.https_default_port
  443
end

.new(address, port = nil, p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil, p_no_proxy = nil, p_use_ssl = nil) ⇒ Object

Returns a new Net::HTTP object http (but does not open a TCP connection or HTTP session).

With only string argument address given (and ENV undefined or nil), the returned http:

  • Has the given address.
  • Has the default port number, Net::HTTP.default_port (80).
  • Has no proxy.

Example:

http = Net::HTTP.new(hostname)
# => #<Net::HTTP jsonplaceholder.typicode.com:80 open=false>
http.address # => "jsonplaceholder.typicode.com"
http.port    # => 80
http.proxy?  # => false

With integer argument port also given, the returned http has the given port:

http = Net::HTTP.new(hostname, 8000)
# => #<Net::HTTP jsonplaceholder.typicode.com:8000 open=false>
http.port # => 8000

For proxy-defining arguments p_addr through p_no_proxy, see Proxy Server.



1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
# File 'lib/net/http.rb', line 1100

def HTTP.new(address, port = nil, p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil, p_no_proxy = nil, p_use_ssl = nil)
  http = super address, port

  if proxy_class? then # from Net::HTTP::Proxy()
    http.proxy_from_env = @proxy_from_env
    http.proxy_address  = @proxy_address
    http.proxy_port     = @proxy_port
    http.proxy_user     = @proxy_user
    http.proxy_pass     = @proxy_pass
    http.proxy_use_ssl  = @proxy_use_ssl
  elsif p_addr == :ENV then
    http.proxy_from_env = true
  else
    if p_addr && p_no_proxy && !URI::Generic.use_proxy?(address, address, port, p_no_proxy)
      p_addr = nil
      p_port = nil
    end
    http.proxy_address = p_addr
    http.proxy_port    = p_port || default_port
    http.proxy_user    = p_user
    http.proxy_pass    = p_pass
    http.proxy_use_ssl = p_use_ssl
  end

  http
end

.newobjObject

:nodoc:



1068
# File 'lib/net/http.rb', line 1068

alias newobj new

.post(url, data, header = nil) ⇒ Object

Posts data to a host; returns a Net::HTTPResponse object.

Argument url must be a URL; argument data must be a string:

_uri = uri.dup
_uri.path = '/posts'
data = '{"title": "foo", "body": "bar", "userId": 1}'
headers = {'content-type': 'application/json'}
res = Net::HTTP.post(_uri, data, headers) # => #<Net::HTTPCreated 201 Created readbody=true>
puts res.body

Output:

{
"title": "foo",
"body": "bar",
"userId": 1,
"id": 101
}

Related:

  • Net::HTTP::Post: request class for HTTP method POST.
  • Net::HTTP#post: convenience method for HTTP method POST.


857
858
859
860
861
862
# File 'lib/net/http.rb', line 857

def HTTP.post(url, data, header = nil)
  start(url.hostname, url.port,
        :use_ssl => url.scheme == 'https' ) {|http|
    http.post(url, data, header)
  }
end

.post_form(url, params) ⇒ Object

Posts data to a host; returns a Net::HTTPResponse object.

Argument url must be a URI; argument data must be a hash:

_uri = uri.dup
_uri.path = '/posts'
data = {title: 'foo', body: 'bar', userId: 1}
res = Net::HTTP.post_form(_uri, data) # => #<Net::HTTPCreated 201 Created readbody=true>
puts res.body

Output:

{
"title": "foo",
"body": "bar",
"userId": "1",
"id": 101
}


884
885
886
887
888
889
890
891
892
# File 'lib/net/http.rb', line 884

def HTTP.post_form(url, params)
  req = Post.new(url)
  req.form_data = params
  req.basic_auth url.user, url.password if url.user
  start(url.hostname, url.port,
        :use_ssl => url.scheme == 'https' ) {|http|
    http.request(req)
  }
end

.Proxy(p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil, p_use_ssl = nil) ⇒ Object

Creates an HTTP proxy class which behaves like Net::HTTP, but performs all access via the specified proxy.

This class is obsolete. You may pass these same parameters directly to Net::HTTP.new. See Net::HTTP.new for details of the arguments.



1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
# File 'lib/net/http.rb', line 1802

def HTTP.Proxy(p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil, p_use_ssl = nil) #:nodoc:
  return self unless p_addr

  Class.new(self) {
    @is_proxy_class = true

    if p_addr == :ENV then
      @proxy_from_env = true
      @proxy_address = nil
      @proxy_port    = nil
    else
      @proxy_from_env = false
      @proxy_address = p_addr
      @proxy_port    = p_port || default_port
    end

    @proxy_user = p_user
    @proxy_pass = p_pass
    @proxy_use_ssl = p_use_ssl
  }
end

.proxy_class?Boolean

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

Returns:

  • (Boolean)


1826
1827
1828
# File 'lib/net/http.rb', line 1826

def proxy_class?
  defined?(@is_proxy_class) ? @is_proxy_class : false
end

.put(url, data, header = nil) ⇒ Object

Sends a PUT request to the server; returns a Net::HTTPResponse object.

Argument url must be a URL; argument data must be a string:

_uri = uri.dup
_uri.path = '/posts'
data = '{"title": "foo", "body": "bar", "userId": 1}'
headers = {'content-type': 'application/json'}
res = Net::HTTP.put(_uri, data, headers) # => #<Net::HTTPCreated 201 Created readbody=true>
puts res.body

Output:

{
"title": "foo",
"body": "bar",
"userId": 1,
"id": 101
}

Related:

  • Net::HTTP::Put: request class for HTTP method PUT.
  • Net::HTTP#put: convenience method for HTTP method PUT.


920
921
922
923
924
925
# File 'lib/net/http.rb', line 920

def HTTP.put(url, data, header = nil)
  start(url.hostname, url.port,
        :use_ssl => url.scheme == 'https' ) {|http|
    http.put(url, data, header)
  }
end

.socket_typeObject

:nodoc: obsolete



955
956
957
# File 'lib/net/http.rb', line 955

def HTTP.socket_type   #:nodoc: obsolete
  BufferedIO
end

.start(address, *arg, &block) ⇒ Object

:call-seq:

HTTP.start(address, port = nil, p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil, opts) -> http
HTTP.start(address, port = nil, p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil, opts) {|http| ... } -> object

Creates a new Net::HTTP object, http, via Net::HTTP.new:

  • For arguments address and port, see Net::HTTP.new.
  • For proxy-defining arguments p_addr through p_pass, see Proxy Server.
  • For argument opts, see below.

With no block given:

  • Calls http.start with no block (see #start), which opens a TCP connection and HTTP session.

  • Returns http.

  • The caller should call #finish to close the session:

    http = Net::HTTP.start(hostname)
    http.started? # => true
    http.finish
    http.started? # => false
    

With a block given:

  • Calls http.start with the block (see #start), which:

  • Opens a TCP connection and HTTP session.

  • Calls the block, which may make any number of requests to the host.

  • Closes the HTTP session and TCP connection on block exit.

  • Returns the block's value object.

  • Returns object.

Example:

hostname = 'jsonplaceholder.typicode.com'
Net::HTTP.start(hostname) do |http|
puts http.get('/todos/1').body
puts http.get('/todos/2').body
end

Output:

{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
}

If the last argument given is a hash, it is the opts hash, where each key is a method or accessor to be called, and its value is the value to be set.

The keys may include:

  • #ca_file
  • #ca_path
  • #cert
  • #cert_store
  • #ciphers
  • #close_on_empty_response
  • ipaddr (calls #ipaddr=)
  • #keep_alive_timeout
  • #key
  • #open_timeout
  • #read_timeout
  • #ssl_timeout
  • #ssl_version
  • use_ssl (calls #use_ssl=)
  • #verify_callback
  • #verify_depth
  • #verify_mode
  • #write_timeout

Note: If port is nil and opts is a truthy value, the value passed to new is Net::HTTP.https_default_port, not port.



1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
# File 'lib/net/http.rb', line 1045

def HTTP.start(address, *arg, &block) # :yield: +http+
  arg.pop if opt = Hash.try_convert(arg[-1])
  port, p_addr, p_port, p_user, p_pass = *arg
  p_addr = :ENV if arg.size < 2
  port = https_default_port if !port && opt && opt[:use_ssl]
  http = new(address, port, p_addr, p_port, p_user, p_pass)
  http.ipaddr = opt[:ipaddr] if opt && opt[:ipaddr]

  if opt
    if opt[:use_ssl]
      opt = {verify_mode: OpenSSL::SSL::VERIFY_PEER}.update(opt)
    end
    http.methods.grep(/\A(\w+)=\z/) do |meth|
      key = $1.to_sym
      opt.key?(key) or next
      http.__send__(meth, opt[key])
    end
  end

  http.start(&block)
end