Henley Wing Chiu
Henley Wing Chiu

Reputation: 22515

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.

Upvotes: 6

Views: 7726

Answers (2)

fmendez
fmendez

Reputation: 7338

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.

Upvotes: 5

toch
toch

Reputation: 3945

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

Upvotes: 9

Related Questions