In the following code, we have to join the url.path
and url.query
ourselves using the ?
character? Is there a more elegant way to do it? I have to use net/http
because in some situations I want to put a string in the header for the user-agent as well.
require 'net/http'
url_string = 'http://www.time.gov/timezone.cgi?Pacific/d/-8'
url = URI.parse(url_string)
response = Net::HTTP.start(url.host, url.port) do |http|
http.get(url.path + '?' + url.query)
end
puts response.body[/<td.*(\d\d:\d\d:\d\d)/, 1]
Net::HTTP provides a rich library which can be used to build HTTP user-agents. For more details about HTTP see [RFC2616](www.ietf.org/rfc/rfc2616.txt). Net::HTTP is designed to work closely with URI.
POST request with do block Using the object created in the do block we use the . body object method to add our params encoded using URI. There are other useful methods like request. headers['Content-Type'] = 'application/json' here setting the request's content type, or request.
Use the request_uri
method on the URI object:
http://www.ruby-doc.org/stdlib/libdoc/uri/rdoc/classes/URI/HTTP.html#M009499
Updated version of your code:
require 'net/http'
url_string = 'http://www.time.gov/timezone.cgi?Pacific/d/-8'
url = URI.parse(url_string)
response = Net::HTTP.start(url.host, url.port) do |http|
http.get(url.request_uri)
end
puts response.body[/<td.*(\d\d:\d\d:\d\d)/, 1]
You can use URI#request_uri
From the docs:
Returns the full path for an HTTP request, as required by Net::HTTP::Get.
If the URI contains a query, the full path is URI#path + ’?’ + URI#query. Otherwise, the path is simply URI#path.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With