在Ruby中发出HEAD请求

Kri*_*ish 3 ruby net-http

我是ruby的新手,从python背景我想对URL发出请求并查看一些信息,比如文件是否存在于服务器和时间戳,etag等等,我无法完成红宝石.

在Python中:

import httplib2
print httplib2.Http().request('url.com/file.xml','HEAD')
Run Code Online (Sandbox Code Playgroud)

在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>'
Run Code Online (Sandbox Code Playgroud)

hlh*_*hlh 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
Run Code Online (Sandbox Code Playgroud)

你可以试试这个:

require 'net/http'

url = URI('yoururl.com')

Net::HTTP.start(url.host, url.port){|http|
   response = http.head('/file.xml')
   puts response
}
Run Code Online (Sandbox Code Playgroud)

有一点我注意到了 - 你puts response需要进入街区!否则,变量response不在范围内.

编辑:您还可以将响应视为哈希以获取标头的值:

response.each_value { |value| puts value }
Run Code Online (Sandbox Code Playgroud)


Mik*_*e D 5

我知道已经解决了这个问题,但是我也不得不经历一些麻烦。这是更具体的开始:

#!/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 }
Run Code Online (Sandbox Code Playgroud)