yeyo
yeyo

Reputation: 3009

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.

Upvotes: 5

Views: 5823

Answers (2)

Renato Zannon
Renato Zannon

Reputation: 29941

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.

Upvotes: 9

ck3g
ck3g

Reputation: 5929

If the optional block is given, the newly created Net::HTTP object is passed to it and closed when the block finishes.

from ruby-doc.org

Upvotes: 2

Related Questions