1. Net::
  2. HTTPSession

class Net::HTTPSession

Class Net::HTTP provides a rich library that implements the client in a client-server model that uses the HTTP request-response protocol. For information about HTTP, see:

About the Examples

Examples here assume thatnet/http has been required (which also requiresuri):

require'net/http'

Many code examples here use these example websites:

Some examples also assume these variables:

uri =URI('https://jsonplaceholder.typicode.com/')uri.freeze# Examples may not modify.hostname =uri.hostname# => "jsonplaceholder.typicode.com"path =uri.path# => "/"port =uri.port# => 443

So that example requests may be written as:

Net::HTTP.get(uri)Net::HTTP.get(hostname,'/index.html')Net::HTTP.start(hostname)do|http|http.get('/todos/1')http.get('/todos/2')end

An example that needs a modifiedURI first duplicatesuri, then modifies the duplicate:

_uri =uri.dup_uri.path ='/todos/1'

Strategies

The methods cited above are convenience methods that, via their few arguments, allow minimal control over the requests. For greater control, consider usingrequest objects.

URIs

On the internet, aURI (Universal Resource Identifier) is a string that identifies a particular resource. It consists of some or all of: scheme, hostname, path, query, and fragment; seeURI syntax.

A RubyURI::Generic object represents an internetURI. It provides, among others, methodsscheme,hostname,path,query, andfragment.

Schemes

An internet URI has ascheme.

The two schemes supported in Net::HTTP are'https' and'http':

uri.scheme# => "https"URI('http://example.com').scheme# => "http"

Hostnames

A hostname identifies a server (host) to which requests may be sent:

hostname =uri.hostname# => "jsonplaceholder.typicode.com"Net::HTTP.start(hostname)do|http|# Some HTTP stuff.end

Paths

A host-specific path identifies a resource on the host:

_uri =uri.dup_uri.path ='/todos/1'hostname =_uri.hostnamepath =_uri.pathNet::HTTP.get(hostname,path)

Queries

A host-specific query adds name/value pairs to the URI:

_uri =uri.dupparams = {userId:1,completed:false}_uri.query =URI.encode_www_form(params)_uri# => #<URI::HTTPS https://jsonplaceholder.typicode.com?userId=1&completed=false>Net::HTTP.get(_uri)

Fragments

AURI fragment has no effect in Net::HTTP; the same data is returned, regardless of whether a fragment is included.

Request Headers

Request headers may be used to pass additional information to the host, similar to arguments passed in a method call; each header is a name/value pair.

Each of the Net::HTTP methods that sends a request to the host has optional argumentheaders, where the headers are expressed as a hash of field-name/value pairs:

headers = {Accept:'application/json',Connection:'Keep-Alive'}Net::HTTP.get(uri,headers)

See lists of both standard request fields and common request fields atRequest Fields. A host may also accept other custom fields.

HTTP Sessions

Asession is a connection between a server (host) and a client that:

See example sessions atStrategies.

Session Using Net::HTTP.start

If you have many requests to make to a single host (and port), consider using singleton methodNet::HTTP.start with a block; the method handles the session automatically by:

In the block, you can use these instance methods, each of which that sends a single request:

Session Using Net::HTTP.start and Net::HTTP.finish

You can manage a session manually using methodsstart andfinish:

http =Net::HTTP.new(hostname)http.starthttp.get('/todos/1')http.get('/todos/2')http.delete('/posts/1')http.finish# Needed to free resources.

Single-Request Session

Certain convenience methods automatically handle a session by:

Such methods that send GET requests:

Such methods that send POST requests:

HTTP Requests and Responses

Many of the methods above are convenience methods, each of which sends a request and returns a string without directly using Net::HTTPRequest and Net::HTTPResponse objects.

You can, however, directly create a request object, send the request, and retrieve the response object; see:

Following Redirection

Each returned response is an instance of a subclass ofNet::HTTPResponse. See theresponse class hierarchy.

In particular, classNet::HTTPRedirection is the parent of all redirection classes. This allows you to craft a case statement to handle redirections properly:

deffetch(uri,limit =10)# You should choose a better exception.raiseArgumentError,'Too many HTTP redirects'iflimit==0res =Net::HTTP.get_response(URI(uri))casereswhenNet::HTTPSuccess# Any success class.reswhenNet::HTTPRedirection# Any redirection class.location =res['Location']warn"Redirected to #{location}"fetch(location,limit-1)else# Any other class.res.valueendendfetch(uri)

Basic Authentication

Basic authentication is performed according toRFC2617:

req =Net::HTTP::Get.new(uri)req.basic_auth('user','pass')res =Net::HTTP.start(hostname)do|http|http.request(req)end

Streaming Response Bodies

By default Net::HTTP reads an entire response into memory. If you are handling large files or wish to implement a progress bar you can instead stream the body directly to anIO.

Net::HTTP.start(hostname)do|http|req =Net::HTTP::Get.new(uri)http.request(req)do|res|open('t.tmp','w')do|f|res.read_bodydo|chunk|f.writechunkendendendend

HTTPS

HTTPS is enabled for an HTTP connection byNet::HTTP#use_ssl=:

Net::HTTP.start(hostname,:use_ssl=>true)do|http|req =Net::HTTP::Get.new(uri)res =http.request(req)end

Or if you simply want to make a GET request, you may pass in aURI object that has an HTTPS URL. Net::HTTP automatically turns on TLS verification if theURI object has a ‘https’URI scheme:

uri# => #<URI::HTTPS https://jsonplaceholder.typicode.com/>Net::HTTP.get(uri)

Proxy Server

An HTTP object can have aproxy server.

You can create an HTTP object with a proxy server using methodNet::HTTP.new or methodNet::HTTP.start.

The proxy may be defined either by argumentp_addr or by environment variable'http_proxy'.

Proxy Using Argumentp_addr as a String

When argumentp_addr is a string hostname, the returnedhttp has the given host as its proxy:

http =Net::HTTP.new(hostname,nil,'proxy.example')http.proxy?# => truehttp.proxy_from_env?# => falsehttp.proxy_address# => "proxy.example"# These use default values.http.proxy_port# => 80http.proxy_user# => nilhttp.proxy_pass# => nil

The port, username, and password for the proxy may also be given:

http =Net::HTTP.new(hostname,nil,'proxy.example',8000,'pname','ppass')# => #<Net::HTTP jsonplaceholder.typicode.com:80 open=false>http.proxy?# => truehttp.proxy_from_env?# => falsehttp.proxy_address# => "proxy.example"http.proxy_port# => 8000http.proxy_user# => "pname"http.proxy_pass# => "ppass"

Proxy Using ‘ENV['http_proxy']

When environment variable'http_proxy' is set to a URI string, the returnedhttp will have the server at thatURI as its proxy; note that the URI string must have a protocol such as'http' or'https':

ENV['http_proxy'] ='http://example.com'http =Net::HTTP.new(hostname)http.proxy?# => truehttp.proxy_from_env?# => truehttp.proxy_address# => "example.com"# These use default values.http.proxy_port# => 80http.proxy_user# => nilhttp.proxy_pass# => nil

The URI string may include proxy username, password, and port number:

ENV['http_proxy'] ='http://pname:ppass@example.com:8000'http =Net::HTTP.new(hostname)http.proxy?# => truehttp.proxy_from_env?# => truehttp.proxy_address# => "example.com"http.proxy_port# => 8000http.proxy_user# => "pname"http.proxy_pass# => "ppass"

Filtering Proxies

With methodNet::HTTP.new (but notNet::HTTP.start), you can use argumentp_no_proxy to filter proxies:

Compression and Decompression

Net::HTTP does not compress the body of a request before sending.

By default, Net::HTTP adds header'Accept-Encoding' to a newrequest object:

Net::HTTP::Get.new(uri)['Accept-Encoding']# => "gzip;q=1.0,deflate;q=0.6,identity;q=0.3"

This requests the server to zip-encode the response body if there is one; the server is not required to do so.

Net::HTTP does not automatically decompress a response body if the response has header'Content-Range'.

Otherwise decompression (or not) depends on the value of headerContent-Encoding:

What’s Here

First, what’s elsewhere. ClassNet::HTTP:

This is a categorized summary of methods and attributes.

Net::HTTP Objects

Sessions

Connections

Requests

Responses

Proxies

Security

Addresses and Ports

HTTP Version

Debugging

Attributes

default_configuration[RW]

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# => 60http.read_timeout# => 1http.write_timeout# => 1
proxy_address[R]

Returns the address of the proxy host, ornil if none; seeProxy Server atNet::HTTP.

proxy_pass[R]

Returns the password for accessing the proxy, ornil if none; seeProxy Server atNet::HTTP.

proxy_port[R]

Returns the port number of the proxy host, ornil if none; seeProxy Server atNet::HTTP.

proxy_use_ssl[R]

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

proxy_user[R]

Returns the user name for accessing the proxy, ornil if none; seeProxy Server atNet::HTTP.

address[R]

Returns the string host name or host IP given as argumentaddress in::new.

ca_file[RW]

Sets or returns the path to a CA certification file in PEM format.

ca_path[RW]

Sets or returns the path of to CA directory containing certification files in PEM format.

cert[RW]

Sets or returns theOpenSSL::X509::Certificate object to be used for client certification.

cert_store[RW]

Sets or returns the X509::Store to be used for verifying peer certificate.

ciphers[RW]

Sets or returns the available SSL ciphers. See:SSL::SSLContext#ciphers=.

close_on_empty_response[RW]

Sets or returns whether to close the connection when the response is empty; initiallyfalse.

continue_timeout[R]

Returns the continue timeout value; seecontinue_timeout=.

extra_chain_cert[RW]

Sets or returns the extra X509 certificates to be added to the certificate chain. See:SSL::SSLContext#add_certificate.

ignore_eof[RW]

Sets or returns whether to ignore end-of-file when reading a response body withContent-Length headers; initiallytrue.

keep_alive_timeout[RW]

Sets or returns the numeric (Integer or Float) number of seconds to keep the connection open after a request is sent; initially 2. If a new request is made during the given interval, the still-open connection is used; otherwise the connection will have been closed and a new connection is opened.

key[RW]

Sets or returns theOpenSSL::PKey::RSA orOpenSSL::PKey::DSA object.

local_host[RW]

Sets or returns the string local host used to establish the connection; initiallynil.

local_port[RW]

Sets or returns the integer local port used to establish the connection; initiallynil.

max_retries[R]

Returns the maximum number of times to retry an idempotent request; seemax_retries=.

max_version[RW]

Sets or returns the maximum SSL version. See:SSL::SSLContext#max_version=.

min_version[RW]

Sets or returns the minimum SSL version. See:SSL::SSLContext#min_version=.

open_timeout[RW]

Sets or returns the numeric (Integer or Float) number of seconds to wait for a connection to open; initially 60. If the connection is not made in the given interval, an exception is raised.

port[R]

Returns the integer port number given as argumentport in::new.

proxy_address[W]

Sets the proxy address; seeProxy Server.

proxy_from_env[W]

Sets whether to determine the proxy from environment variable ‘ENV['http_proxy']’; seeProxy UsingENV.

proxy_pass[W]

Sets the proxy password; seeProxy Server.

proxy_port[W]

Sets the proxy port; seeProxy Server.

proxy_use_ssl[W]

Sets wheter the proxy uses SSL; seeProxy Server.

proxy_user[W]

Sets the proxy user; seeProxy Server.

read_timeout[R]

Returns the numeric (Integer or Float) number of seconds to wait for one block to be read (via one read(2) call); seeread_timeout=.

response_body_encoding[R]

Returns the encoding to use for the response body; seeresponse_body_encoding=.

ssl_timeout[RW]

Sets or returns the SSL timeout seconds.

ssl_version[RW]

Sets or returns the SSL version. See:SSL::SSLContext#ssl_version=.

verify_callback[RW]

Sets or returns the callback for the server certification verification.

verify_depth[RW]

Sets or returns the maximum depth for the certificate chain verification.

verify_hostname[RW]

Sets or returns whether to verify that the server certificate is valid for the hostname. See:SSL::SSLContext#verify_hostname=.

verify_mode[RW]

Sets or returns the flags for server the certification verification at the beginning of the SSL/TLS session. OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER are acceptable.

write_timeout[R]

Returns the numeric (Integer or Float) number of seconds to wait for one block to be written (via one write(2) call); seewrite_timeout=.

Public Class Methods

Source
# File lib/net/http.rb, line 935defHTTP.default_porthttp_default_port()end

Returns integer80, the default port to use for HTTP requests:

Net::HTTP.default_port# => 80
Source
# File lib/net/http.rb, line 804defHTTP.get(uri_or_host,path_or_headers =nil,port =nil)get_response(uri_or_host,path_or_headers,port).bodyend

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

With string argumentshostname andpath:

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

Output:

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

WithURI objecturi and optional hash argumentheaders:

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

Related:

Source
# File lib/net/http.rb, line 763defHTTP.get_print(uri_or_host,path_or_headers =nil,port =nil)get_response(uri_or_host,path_or_headers,port) {|res|res.read_bodydo|chunk|$stdout.printchunkend  }nilend

LikeNet::HTTP.get, but writes the returned body to $stdout; returnsnil.

Source
# File lib/net/http.rb, line 814defHTTP.get_response(uri_or_host,path_or_headers =nil,port =nil,&block)ifpath_or_headers&&!path_or_headers.is_a?(Hash)host =uri_or_hostpath =path_or_headersnew(host,port||HTTP.default_port).start {|http|returnhttp.request_get(path,&block)    }elseuri =uri_or_hostheaders =path_or_headersstart(uri.hostname,uri.port,:use_ssl=>uri.scheme=='https') {|http|returnhttp.request_get(uri,headers,&block)    }endend

LikeNet::HTTP.get, but returns aNet::HTTPResponse object instead of the body string.

Source
# File lib/net/http.rb, line 943defHTTP.http_default_port80end

Returns integer80, the default port to use for HTTP requests:

Net::HTTP.http_default_port# => 80
Source
# File lib/net/http.rb, line 951defHTTP.https_default_port443end

Returns integer443, the default port to use for HTTPS requests:

Net::HTTP.https_default_port# => 443
Source
# File lib/net/http.rb, line 1100defHTTP.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 =superaddress,portifproxy_class?then# from Net::HTTP::Proxy()http.proxy_from_env =@proxy_from_envhttp.proxy_address  =@proxy_addresshttp.proxy_port     =@proxy_porthttp.proxy_user     =@proxy_userhttp.proxy_pass     =@proxy_passhttp.proxy_use_ssl  =@proxy_use_sslelsifp_addr==:ENVthenhttp.proxy_from_env =trueelseifp_addr&&p_no_proxy&&!URI::Generic.use_proxy?(address,address,port,p_no_proxy)p_addr =nilp_port =nilendhttp.proxy_address =p_addrhttp.proxy_port    =p_port||default_porthttp.proxy_user    =p_userhttp.proxy_pass    =p_passhttp.proxy_use_ssl =p_use_sslendhttpend

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

With only string argumentaddress given (andENV['http_proxy'] undefined ornil), the returnedhttp:

Example:

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

With integer argumentport also given, the returnedhttp has the given port:

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

For proxy-defining argumentsp_addr throughp_no_proxy, seeProxy Server.

Calls superclass method
Source
# File lib/net/http.rb, line 857defHTTP.post(url,data,header =nil)start(url.hostname,url.port,:use_ssl=>url.scheme=='https' ) {|http|http.post(url,data,header)  }end

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

Argumenturl must be a URL; argumentdata 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>putsres.body

Output:

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

Related:

Source
# File lib/net/http.rb, line 884defHTTP.post_form(url,params)req =Post.new(url)req.form_data =paramsreq.basic_authurl.user,url.passwordifurl.userstart(url.hostname,url.port,:use_ssl=>url.scheme=='https' ) {|http|http.request(req)  }end

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

Argumenturl must be aURI; argumentdata 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>putsres.body

Output:

{"title":"foo","body":"bar","userId":"1","id":101}
Source
# File lib/net/http.rb, line 1855defproxy_class?defined?(@is_proxy_class)?@is_proxy_class:falseend

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

Source
# File lib/net/http.rb, line 920defHTTP.put(url,data,header =nil)start(url.hostname,url.port,:use_ssl=>url.scheme=='https' ) {|http|http.put(url,data,header)  }end

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

Argumenturl must be a URL; argumentdata 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>putsres.body

Output:

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

Related:

Source
# File lib/net/http.rb, line 1045defHTTP.start(address,*arg,&block)# :yield: +http+arg.popifopt =Hash.try_convert(arg[-1])port,p_addr,p_port,p_user,p_pass =*argp_addr =:ENVifarg.size<2port =https_default_portif!port&&opt&&opt[:use_ssl]http =new(address,port,p_addr,p_port,p_user,p_pass)http.ipaddr =opt[:ipaddr]ifopt&&opt[:ipaddr]ifoptifopt[:use_ssl]opt = {verify_mode:OpenSSL::SSL::VERIFY_PEER}.update(opt)endhttp.methods.grep(/\A(\w+)=\z/)do|meth|key =$1.to_symopt.key?(key)ornexthttp.__send__(meth,opt[key])endendhttp.start(&block)end

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

  • For argumentsaddress andport, seeNet::HTTP.new.

  • For proxy-defining argumentsp_addr throughp_pass, seeProxy Server.

  • For argumentopts, see below.

With no block given:

  • Callshttp.start with no block (seestart), which opens a TCP connection and HTTP session.

  • Returnshttp.

  • The caller should callfinish to close the session:

    http =Net::HTTP.start(hostname)http.started?# => truehttp.finishhttp.started?# => false

With a block given:

  • Callshttp.start with 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 valueobject.

  • Returnsobject.

Example:

hostname ='jsonplaceholder.typicode.com'Net::HTTP.start(hostname)do|http|putshttp.get('/todos/1').bodyputshttp.get('/todos/2').bodyend

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 theopts 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: Ifport isnil andopts[:use_ssl] is a truthy value, the value passed tonew isNet::HTTP.https_default_port, notport.

Source
# File lib/net/http.rb, line 738defHTTP.version_1_2trueend

Returnstrue; retained for compatibility.

Source
# File lib/net/http.rb, line 743defHTTP.version_1_2?trueend

Returnstrue; retained for compatibility.

Public Instance Methods

Source
# File lib/net/http.rb, line 1455defcontinue_timeout=(sec)@socket.continue_timeout =secif@socket@continue_timeout =secend

Sets the continue timeout value, which is the number of seconds to wait for an expected 100 Continue response. If the HTTP object does not receive a response in this many seconds it sends the request body.

Source
# File lib/net/http.rb, line 2227defcopy(path,initheader =nil)request(Copy.new(path,initheader))end

Sends a COPY request to the server; returns an instance of a subclass ofNet::HTTPResponse.

The request is based on theNet::HTTP::Copy object created from stringpath and initial headers hashinitheader.

http =Net::HTTP.new(hostname)http.copy('/todos/1')
Source
# File lib/net/http.rb, line 2201defdelete(path,initheader = {'Depth'=>'Infinity'})request(Delete.new(path,initheader))end

Sends a DELETE request to the server; returns an instance of a subclass ofNet::HTTPResponse.

The request is based on theNet::HTTP::Delete object created from stringpath and initial headers hashinitheader.

http =Net::HTTP.new(hostname)http.delete('/todos/1')
Source
# File lib/net/http.rb, line 1648deffinishraiseIOError,'HTTP session not yet started'unlessstarted?do_finishend

Finishes the HTTP session:

http =Net::HTTP.new(hostname)http.starthttp.started?# => truehttp.finish# => nilhttp.started?# => false

RaisesIOError if not in a session.

Source
# File lib/net/http.rb, line 2013defget(path,initheader =nil,dest =nil,&block)# :yield: +body_segment+res =nilrequest(Get.new(path,initheader)) {|r|r.read_bodydest,&blockres =r  }resend

Sends a GET request to the server; returns an instance of a subclass ofNet::HTTPResponse.

The request is based on theNet::HTTP::Get object created from stringpath and initial headers hashinitheader.

With a block given, calls the block with the response body:

http =Net::HTTP.new(hostname)http.get('/todos/1')do|res|presend# => #<Net::HTTPOK 200 OK readbody=true>

Output:

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

With no block given, simply returns the response object:

http.get('/')# => #<Net::HTTPOK 200 OK readbody=true>

Related:

Source
# File lib/net/http.rb, line 2037defhead(path,initheader =nil)request(Head.new(path,initheader))end

Sends a HEAD request to the server; returns an instance of a subclass ofNet::HTTPResponse.

The request is based on theNet::HTTP::Head object created from stringpath and initial headers hashinitheader:

res =http.head('/todos/1')# => #<Net::HTTPOK 200 OK readbody=true>res.body# => nilres.to_hash.take(3)# =>[["date", ["Wed, 15 Feb 2023 15:25:42 GMT"]], ["content-type", ["application/json; charset=utf-8"]], ["connection", ["close"]]]
Source
# File lib/net/http.rb, line 1206definspect"#<#{self.class} #{@address}:#{@port} open=#{started?}>"end

Returns a string representation ofself:

Net::HTTP.new(hostname).inspect# => "#<Net::HTTP jsonplaceholder.typicode.com:80 open=false>"
Source
# File lib/net/http.rb, line 1349defipaddrstarted??@socket.io.peeraddr[3]:@ipaddrend

Returns the IP address for the connection.

If the session has not been started, returns the value set byipaddr=, ornil if it has not been set:

http =Net::HTTP.new(hostname)http.ipaddr# => nilhttp.ipaddr ='172.67.155.76'http.ipaddr# => "172.67.155.76"

If the session has been started, returns the IP address from the socket:

http =Net::HTTP.new(hostname)http.starthttp.ipaddr# => "172.67.155.76"http.finish
Source
# File lib/net/http.rb, line 1361defipaddr=(addr)raiseIOError,"ipaddr value changed, but session already started"ifstarted?@ipaddr =addrend

Sets the IP address for the connection:

http =Net::HTTP.new(hostname)http.ipaddr# => nilhttp.ipaddr ='172.67.155.76'http.ipaddr# => "172.67.155.76"

The IP address may not be set if the session has been started.

Source
# File lib/net/http.rb, line 2147deflock(path,body,initheader =nil)request(Lock.new(path,initheader),body)end

Sends a LOCK request to the server; returns an instance of a subclass ofNet::HTTPResponse.

The request is based on theNet::HTTP::Lock object created from stringpath, stringbody, and initial headers hashinitheader.

data ='{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}'http =Net::HTTP.new(hostname)http.lock('/todos/1',data)
Source
# File lib/net/http.rb, line 1395defmax_retries=(retries)retries =retries.to_intifretries<0raiseArgumentError,'max_retries should be non-negative integer number'end@max_retries =retriesend

Sets the maximum number of times to retry an idempotent request in case of Net::ReadTimeout,IOError,EOFError, Errno::ECONNRESET, Errno::ECONNABORTED, Errno::EPIPE,OpenSSL::SSL::SSLError,Timeout::Error. The initial value is 1.

Argumentretries must be a non-negative numeric value:

http =Net::HTTP.new(hostname)http.max_retries =2# => 2http.max_retries# => 2
Source
# File lib/net/http.rb, line 2241defmkcol(path,body =nil,initheader =nil)request(Mkcol.new(path,initheader),body)end

Sends a MKCOL request to the server; returns an instance of a subclass ofNet::HTTPResponse.

The request is based on theNet::HTTP::Mkcol object created from stringpath, stringbody, and initial headers hashinitheader.

data ='{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}'http.mkcol('/todos/1',data)http =Net::HTTP.new(hostname)
Source
# File lib/net/http.rb, line 2214defmove(path,initheader =nil)request(Move.new(path,initheader))end

Sends a MOVE request to the server; returns an instance of a subclass ofNet::HTTPResponse.

The request is based on theNet::HTTP::Move object created from stringpath and initial headers hashinitheader.

http =Net::HTTP.new(hostname)http.move('/todos/1')
Source
# File lib/net/http.rb, line 2174defoptions(path,initheader =nil)request(Options.new(path,initheader))end

Sends an Options request to the server; returns an instance of a subclass ofNet::HTTPResponse.

The request is based on theNet::HTTP::Options object created from stringpath and initial headers hashinitheader.

http =Net::HTTP.new(hostname)http.options('/')
Source
# File lib/net/http.rb, line 2100defpatch(path,data,initheader =nil,dest =nil,&block)# :yield: +body_segment+send_entity(path,data,initheader,dest,Patch,&block)end

Sends a PATCH request to the server; returns an instance of a subclass ofNet::HTTPResponse.

The request is based on theNet::HTTP::Patch object created from stringpath, stringdata, and initial headers hashinitheader.

With a block given, calls the block with the response body:

data ='{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}'http =Net::HTTP.new(hostname)http.patch('/todos/1',data)do|res|presend# => #<Net::HTTPOK 200 OK readbody=true>

Output:

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

With no block given, simply returns the response object:

http.patch('/todos/1',data)# => #<Net::HTTPCreated 201 Created readbody=true>
Source
# File lib/net/http.rb, line 1597defpeer_certifnotuse_ssl?ornot@socketreturnnilend@socket.io.peer_certend

Returns the X509 certificate chain (an array of strings) for the session’s socket peer, ornil if none.

Source
# File lib/net/http.rb, line 2071defpost(path,data,initheader =nil,dest =nil,&block)# :yield: +body_segment+send_entity(path,data,initheader,dest,Post,&block)end

Sends a POST request to the server; returns an instance of a subclass ofNet::HTTPResponse.

The request is based on theNet::HTTP::Post object created from stringpath, stringdata, and initial headers hashinitheader.

With a block given, calls the block with the response body:

data ='{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}'http =Net::HTTP.new(hostname)http.post('/todos',data)do|res|presend# => #<Net::HTTPCreated 201 Created readbody=true>

Output:

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

With no block given, simply returns the response object:

http.post('/todos',data)# => #<Net::HTTPCreated 201 Created readbody=true>

Related:

Source
# File lib/net/http.rb, line 2188defpropfind(path,body =nil,initheader = {'Depth'=>'0'})request(Propfind.new(path,initheader),body)end

Sends a PROPFIND request to the server; returns an instance of a subclass ofNet::HTTPResponse.

The request is based on theNet::HTTP::Propfind object created from stringpath, stringbody, and initial headers hashinitheader.

data ='{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}'http =Net::HTTP.new(hostname)http.propfind('/todos/1',data)
Source
# File lib/net/http.rb, line 2133defproppatch(path,body,initheader =nil)request(Proppatch.new(path,initheader),body)end

Sends a PROPPATCH request to the server; returns an instance of a subclass ofNet::HTTPResponse.

The request is based on theNet::HTTP::Proppatch object created from stringpath, stringbody, and initial headers hashinitheader.

data ='{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}'http =Net::HTTP.new(hostname)http.proppatch('/todos/1',data)
Source
# File lib/net/http.rb, line 1881defproxy?!!(@proxy_from_env?proxy_uri:@proxy_address)end

Returnstrue if a proxy server is defined,false otherwise; seeProxy Server.

Source
# File lib/net/http.rb, line 1903defproxy_addressif@proxy_from_envthenproxy_uri&.hostnameelse@proxy_addressendend

Returns the address of the proxy server, if defined,nil otherwise; seeProxy Server.

Source
# File lib/net/http.rb, line 1888defproxy_from_env?@proxy_from_envend

Returnstrue if the proxy server is defined in the environment,false otherwise; seeProxy Server.

Source
# File lib/net/http.rb, line 1934defproxy_passif@proxy_from_envpass =proxy_uri&.passwordunescape(pass)ifpasselse@proxy_passendend

Returns the password of the proxy server, if defined,nil otherwise; seeProxy Server.

Source
# File lib/net/http.rb, line 1913defproxy_portif@proxy_from_envthenproxy_uri&.portelse@proxy_portendend

Returns the port number of the proxy server, if defined,nil otherwise; seeProxy Server.

Source
# File lib/net/http.rb, line 1923defproxy_userif@proxy_from_envuser =proxy_uri&.userunescape(user)ifuserelse@proxy_userendend

Returns the user name of the proxy server, if defined,nil otherwise; seeProxy Server.

Source
# File lib/net/http.rb, line 2119defput(path,data,initheader =nil)request(Put.new(path,initheader),data)end

Sends a PUT request to the server; returns an instance of a subclass ofNet::HTTPResponse.

The request is based on theNet::HTTP::Put object created from stringpath, stringdata, and initial headers hashinitheader.

data ='{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}'http =Net::HTTP.new(hostname)http.put('/todos/1',data)# => #<Net::HTTPOK 200 OK readbody=true>

Related:

Source
# File lib/net/http.rb, line 1418defread_timeout=(sec)@socket.read_timeout =secif@socket@read_timeout =secend

Sets the read timeout, in seconds, forself to integersec; the initial value is 60.

Argumentsec must be a non-negative numeric value:

http =Net::HTTP.new(hostname)http.read_timeout# => 60http.get('/todos/1')# => #<Net::HTTPOK 200 OK readbody=true>http.read_timeout =0http.get('/todos/1')# Raises Net::ReadTimeout.
Source
# File lib/net/http.rb, line 2399defrequest(req,body =nil,&block)# :yield: +response+unlessstarted?start {req['connection']||='close'returnrequest(req,body,&block)    }endifproxy_user()req.proxy_basic_authproxy_user(),proxy_pass()unlessuse_ssl?endreq.set_body_internalbodyres =transport_request(req,&block)ifsspi_auth?(res)sspi_auth(req)res =transport_request(req,&block)endresend

Sends the given requestreq to the server; forms the response into aNet::HTTPResponse object.

The givenreq must be an instance of asubclass of Net::HTTPRequest. Argumentbody should be given only if needed for the request.

With no block given, returns the response object:

http =Net::HTTP.new(hostname)req =Net::HTTP::Get.new('/todos/1')http.request(req)# => #<Net::HTTPOK 200 OK readbody=true>req =Net::HTTP::Post.new('/todos')http.request(req,'xyzzy')# => #<Net::HTTPCreated 201 Created readbody=true>

With a block given, calls the block with the response and returns the response:

req =Net::HTTP::Get.new('/todos/1')http.request(req)do|res|presend# => #<Net::HTTPOK 200 OK readbody=true>

Output:

#<Net::HTTPOK 200 OK readbody=false>
Source
# File lib/net/http.rb, line 2280defrequest_get(path,initheader =nil,&block)# :yield: +response+request(Get.new(path,initheader),&block)end

Sends a GET request to the server; forms the response into aNet::HTTPResponse object.

The request is based on theNet::HTTP::Get object created from stringpath and initial headers hashinitheader.

With no block given, returns the response object:

http =Net::HTTP.new(hostname)http.request_get('/todos')# => #<Net::HTTPOK 200 OK readbody=true>

With a block given, calls the block with the response object and returns the response object:

http.request_get('/todos')do|res|presend# => #<Net::HTTPOK 200 OK readbody=true>

Output:

#<Net::HTTPOK 200 OK readbody=false>
Source
# File lib/net/http.rb, line 2293defrequest_head(path,initheader =nil,&block)request(Head.new(path,initheader),&block)end

Sends a HEAD request to the server; returns an instance of a subclass ofNet::HTTPResponse.

The request is based on theNet::HTTP::Head object created from stringpath and initial headers hashinitheader.

http =Net::HTTP.new(hostname)http.head('/todos/1')# => #<Net::HTTPOK 200 OK readbody=true>
Source
# File lib/net/http.rb, line 2320defrequest_post(path,data,initheader =nil,&block)# :yield: +response+requestPost.new(path,initheader),data,&blockend

Sends a POST request to the server; forms the response into aNet::HTTPResponse object.

The request is based on theNet::HTTP::Post object created from stringpath, stringdata, and initial headers hashinitheader.

With no block given, returns the response object:

http =Net::HTTP.new(hostname)http.post('/todos','xyzzy')# => #<Net::HTTPCreated 201 Created readbody=true>

With a block given, calls the block with the response body and returns the response object:

http.post('/todos','xyzzy')do|res|presend# => #<Net::HTTPCreated 201 Created readbody=true>

Output:

"{\n  \"xyzzy\": \"\",\n  \"id\": 201\n}"
Source
# File lib/net/http.rb, line 1300defresponse_body_encoding=(value)value =Encoding.find(value)ifvalue.is_a?(String)@response_body_encoding =valueend

Sets the encoding to be used for the response body; returns the encoding.

The givenvalue may be:

  • AnEncoding object.

  • The name of an encoding.

  • An alias for an encoding name.

SeeEncoding.

Examples:

http =Net::HTTP.new(hostname)http.response_body_encoding =Encoding::US_ASCII# => #<Encoding:US-ASCII>http.response_body_encoding ='US-ASCII'# => "US-ASCII"http.response_body_encoding ='ASCII'# => "ASCII"
Source
# File lib/net/http.rb, line 2363defsend_request(name,path,data =nil,header =nil)has_response_body =name!='HEAD'r =HTTPGenericRequest.new(name,(data?true:false),has_response_body,path,header)requestr,dataend

Sends an HTTP request to the server; returns an instance of a subclass ofNet::HTTPResponse.

The request is based on theNet::HTTPRequest object created from stringpath, stringdata, and initial headers hashheader. That object is an instance of thesubclass of Net::HTTPRequest, that corresponds to the given uppercase stringname, which must be anHTTP request method or aWebDAV request method.

Examples:

http =Net::HTTP.new(hostname)http.send_request('GET','/todos/1')# => #<Net::HTTPOK 200 OK readbody=true>http.send_request('POST','/todos','xyzzy')# => #<Net::HTTPCreated 201 Created readbody=true>
Source
# File lib/net/http.rb, line 1259defset_debug_output(output)warn'Net::HTTP#set_debug_output called after HTTP started',uplevel:1ifstarted?@debug_output =outputend

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

Sets the output stream for debugging:

http =Net::HTTP.new(hostname)File.open('t.tmp','w')do|file|http.set_debug_output(file)http.starthttp.get('/nosuch/1')http.finishendputsFile.read('t.tmp')

Output:

opening connection to jsonplaceholder.typicode.com:80...opened<- "GET /nosuch/1 HTTP/1.1\r\nAccept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3\r\nAccept: */*\r\nUser-Agent: Ruby\r\nHost: jsonplaceholder.typicode.com\r\n\r\n"-> "HTTP/1.1 404 Not Found\r\n"-> "Date: Mon, 12 Dec 2022 21:14:11 GMT\r\n"-> "Content-Type: application/json; charset=utf-8\r\n"-> "Content-Length: 2\r\n"-> "Connection: keep-alive\r\n"-> "X-Powered-By: Express\r\n"-> "X-Ratelimit-Limit: 1000\r\n"-> "X-Ratelimit-Remaining: 999\r\n"-> "X-Ratelimit-Reset: 1670879660\r\n"-> "Vary: Origin, Accept-Encoding\r\n"-> "Access-Control-Allow-Credentials: true\r\n"-> "Cache-Control: max-age=43200\r\n"-> "Pragma: no-cache\r\n"-> "Expires: -1\r\n"-> "X-Content-Type-Options: nosniff\r\n"-> "Etag: W/\"2-vyGp6PvFo4RvsFtPoIWeCReyIC8\"\r\n"-> "Via: 1.1 vegur\r\n"-> "CF-Cache-Status: MISS\r\n"-> "Server-Timing: cf-q-config;dur=1.3000000762986e-05\r\n"-> "Report-To: {\"endpoints\":[{\"url\":\"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=yOr40jo%2BwS1KHzhTlVpl54beJ5Wx2FcG4gGV0XVrh3X9OlR5q4drUn2dkt5DGO4GDcE%2BVXT7CNgJvGs%2BZleIyMu8CLieFiDIvOviOY3EhHg94m0ZNZgrEdpKD0S85S507l1vsEwEHkoTm%2Ff19SiO\"}],\"group\":\"cf-nel\",\"max_age\":604800}\r\n"-> "NEL: {\"success_fraction\":0,\"report_to\":\"cf-nel\",\"max_age\":604800}\r\n"-> "Server: cloudflare\r\n"-> "CF-RAY: 778977dc484ce591-DFW\r\n"-> "alt-svc: h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400\r\n"-> "\r\n"reading 2 bytes...-> "{}"read 2 bytesConn keep-alive
Source
# File lib/net/http.rb, line 1625defstart# :yield: httpraiseIOError,'HTTP session already opened'if@startedifblock_given?begindo_startreturnyield(self)ensuredo_finishendenddo_startselfend

Starts an HTTP session.

Without a block, returnsself:

http =Net::HTTP.new(hostname)# => #<Net::HTTP jsonplaceholder.typicode.com:80 open=false>http.start# => #<Net::HTTP jsonplaceholder.typicode.com:80 open=true>http.started?# => truehttp.finish

With a block, calls the block withself, finishes the session when the block exits, and returns the block’s value:

http.startdo|http|httpend# => #<Net::HTTP jsonplaceholder.typicode.com:80 open=false>http.started?# => false
Source
# File lib/net/http.rb, line 1488defstarted?@startedend

Returnstrue if the HTTP session has been started:

http =Net::HTTP.new(hostname)http.started?# => falsehttp.starthttp.started?# => truehttp.finish# => nilhttp.started?# => falseNet::HTTP.start(hostname)do|http|http.started?end# => truehttp.started?# => false
Source
# File lib/net/http.rb, line 2254deftrace(path,initheader =nil)request(Trace.new(path,initheader))end

Sends a TRACE request to the server; returns an instance of a subclass ofNet::HTTPResponse.

The request is based on theNet::HTTP::Trace object created from stringpath and initial headers hashinitheader.

http =Net::HTTP.new(hostname)http.trace('/todos/1')
Source
# File lib/net/http.rb, line 2161defunlock(path,body,initheader =nil)request(Unlock.new(path,initheader),body)end

Sends an UNLOCK request to the server; returns an instance of a subclass ofNet::HTTPResponse.

The request is based on theNet::HTTP::Unlock object created from stringpath, stringbody, and initial headers hashinitheader.

data ='{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}'http =Net::HTTP.new(hostname)http.unlock('/todos/1',data)
Source
# File lib/net/http.rb, line 1510defuse_ssl=(flag)flag =flag?true:falseifstarted?and@use_ssl!=flagraiseIOError,"use_ssl value changed, but session already started"end@use_ssl =flagend

Sets whether a new session is to useTransport Layer Security:

RaisesIOError if attempting to change during a session.

RaisesOpenSSL::SSL::SSLError if the port is not an HTTPS port.

Source
# File lib/net/http.rb, line 1500defuse_ssl?@use_sslend

Returnstrue ifself uses SSL,false otherwise. SeeNet::HTTP#use_ssl=.

Source
# File lib/net/http.rb, line 1442defwrite_timeout=(sec)@socket.write_timeout =secif@socket@write_timeout =secend

Sets the write timeout, in seconds, forself to integersec; the initial value is 60.

Argumentsec must be a non-negative numeric value:

_uri =uri.dup_uri.path ='/posts'body ='bar'*200000data =<<EOF{"title": "foo", "body": "#{body}", "userId": "1"}EOFheaders = {'content-type':'application/json'}http =Net::HTTP.new(hostname)http.write_timeout# => 60http.post(_uri.path,data,headers)# => #<Net::HTTPCreated 201 Created readbody=true>http.write_timeout =0http.post(_uri.path,data,headers)# Raises Net::WriteTimeout.

Private Instance Methods

Source
# File lib/net/http.rb, line 2422defsend_entity(path,data,initheader,dest,type,&block)res =nilrequest(type.new(path,initheader),data) {|r|r.read_bodydest,&blockres =r  }resend

Executes a request which uses a representation and returns its body.