Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby, using "net/http", we have to join the url and query using a "?" ourselves?

Tags:

ruby

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]
like image 551
nonopolarity Avatar asked Feb 28 '11 05:02

nonopolarity


People also ask

What is Net HTTP?

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.

How do you create a post request in Ruby?

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.


2 Answers

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]
like image 161
ctcherry Avatar answered Sep 22 '22 00:09

ctcherry


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.

like image 33
Tobias Cohen Avatar answered Sep 22 '22 00:09

Tobias Cohen