在下面的代码中,我们必须使用url.path和url.query来加入?字符?有更优雅的方式吗?我必须使用net / http,因为在某些情况下,我想把字符串放在用户代理的头中.
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]
解决方法
对URI对象使用request_uri方法:
http://www.ruby-doc.org/stdlib/libdoc/uri/rdoc/classes/URI/HTTP.html#M009499
您的代码更新版本:
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]