我对 ruby 有点陌生,有 python 背景 我想向 URL 发出头请求并检查一些信息,例如文件是否存在于服务器上以及时间戳、etag 等,我无法在 RUBY 中完成此操作。
在Python中:
import httplib2
print httplib2.Http().request('url.com/file.xml','HEAD')
在 Ruby 中:我尝试了这个并抛出了一些错误
require 'net/http'
Net::HTTP.start('url.com'){|http|
response = http.head('/file.xml')
}
puts response
SocketError: getaddrinfo: nodename nor servname provided, or not known
from /Users/comcast/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http.rb:877:in `initialize'
from /Users/comcast/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http.rb:877:in `open'
from /Users/comcast/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http.rb:877:in `block in connect'
from /Users/comcast/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/timeout.rb:51:in `timeout'
from /Users/comcast/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http.rb:876:in `connect'
from /Users/comcast/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http.rb:861:in `do_start'
from /Users/comcast/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http.rb:850:in `start'
from /Users/comcast/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/net/http.rb:582:in `start'
from (irb):2
from /Users/comcast/.rvm/rubies/ruby-2.0.0-p0/bin/irb:16:in `<main>'
我意识到这个问题已经得到解答,但我也必须经历一些困难。这是更具体的开始:
#!/usr/bin/env ruby
require 'net/http'
require 'net/https' # for openssl
uri = URI('http://stackoverflow.com')
path = '/questions/16325918/making-head-request-in-ruby'
response=nil
http = Net::HTTP.new(uri.host, uri.port)
# http.use_ssl = true # if using SSL
# http.verify_mode = OpenSSL::SSL::VERIFY_NONE # for example, when using self-signed certs
response = http.head(path)
response.each { |key, value| puts key.ljust(40) + " : " + value }
我认为向 :start 传递一个字符串还不够; 在文档中看起来它需要 URI 对象的主机和端口才能获得正确的地址:
uri = URI('http://example.com/some_path?query=string')
Net::HTTP.start(uri.host, uri.port) do |http|
request = Net::HTTP::Get.new uri
response = http.request request # Net::HTTPResponse object
end
你可以试试这个:
require 'net/http'
url = URI('yoururl.com')
Net::HTTP.start(url.host, url.port){|http|
response = http.head('/file.xml')
puts response
}
我注意到一件事 - 你的
puts response
需要在街区内!否则,变量 response
不在范围内。
编辑:您还可以将响应视为散列以获取标头的值:
response.each_value { |value| puts value }
headers = nil
uri = URI('http://my-bucket.amazonaws.com/filename.mp4')
Net::HTTP.start(uri.host, uri.port) do |http|
headers = http.head(uri.path).to_hash
end
现在您在
headers
中拥有了标题的哈希值