yeyo yeyo - 1 month ago 21
HTTP Question

How to properly close a HTTP connection in Ruby

I've been looking for a proper way to close a HTTP connection and have found nothing yet.

require 'net/http'
require 'uri'

uri = URI.parse("http://www.google.com")

http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new("/")


http.start
resp = http.request request

p resp.body


So far so good, but now when I try to close the connection guessing which method to use:

http.shutdown # error
http.close # error


when I check
ri Net::HTTP.start
, the documentation explicitly says


the caller is responsible for closing it (the connection) upon completion


I don't want to use the block form.

Answer

The method to close the connection is http.finish.

The net/http API is particularly confusing to use. It is generally easier to use a higher-level library instead, such as HTTParty or REST Client, which will provide a more intuitive API and take care of the lower level details for you.