3

我是 ruby​​ 的新手,从 python 背景我想向 URL 发出头部请求并检查一些信息,例如文件是否存在于服务器上以及时间戳、etag 等,我无法完成此操作红宝石。

在 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>'
4

3 回答 3

7

我意识到这已经得到解答,但我也不得不经历一些困难。这里有一些更具体的开始:

#!/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 }
于 2015-03-05T01:26:26.887 回答
6

我认为将字符串传递给 :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 }
于 2013-05-01T20:41:14.570 回答
3
headers = nil

url = URI('http://my-bucket.amazonaws.com/filename.mp4')

Net::HTTP.start(url.host, url.port) do |http|
  headers = http.head(url.path).to_hash
end

现在你有一个标题哈希headers

于 2016-02-27T18:34:40.550 回答