Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby HTTPClient: How to use persistent connections?

How does one use persistent HTTP connections with HTTPClient? Is it just a matter of setting Keep Alive when sending a HTTP Request? The documentation states persistent connections are supported, but doesn't tell us how to use them.

like image 978
Henley Avatar asked Apr 12 '13 16:04

Henley


2 Answers

It's available in Net::HTTP

As written in the doc,

Net::HTTP.start immediately creates a connection to an HTTP server which is kept open for the duration of the block. The connection will remain open for multiple requests in the block if the server indicates it supports persistent connections.

That means all the request you'll do in the block will use the same HTTP connection.

The example from the doc

require 'net/http'

uri = URI('http://google.com/')

Net::HTTP.start(uri.host, uri.port) do |http|
  request = Net::HTTP::Get.new uri.request_uri

  response = http.request request # Net::HTTPResponse object
end
like image 143
toch Avatar answered Nov 18 '22 10:11

toch


As stated in the HttpClient Readme:

you don't have to care HTTP/1.1 persistent connection (httpclient cares instead of you)

That usually means that in the scenario that the server supports HTTP 1.1 persistent connections, the httpclient gem will store and re-use them (the connections) for subsequent requests. In which case, you don't have to worry about it.

like image 5
fmendez Avatar answered Nov 18 '22 08:11

fmendez