Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
Net::HTTPSession.start
# File tmp/rubies/ruby-4.1.0-preview1/lib/net/http.rb, line 1049
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
Creates a new Net::HTTP object, http, via Net::HTTP.new:
-
For arguments
addressandport, seeNet::HTTP.new. -
For proxy-defining arguments
p_addrthroughp_pass, see Proxy Server. -
For argument
opts, see below.
With no block given:
-
Calls
http.startwith no block (seestart), which opens a TCP connection and HTTP session. -
Returns
http. -
The caller should call
finishto close the session:Examplehttp = Net::HTTP.start(hostname) http.started? # => true http.finish http.started? # => false
With a block given:
-
Calls
http.startwith the block (seestart), 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:
Note: If port is nil and opts[:use_ssl] is a truthy value, the value passed to new is Net::HTTP.https_default_port, not port.