ruby - 如何使用修改后的 header 制作 HTTP GET?

标签 ruby http http-headers

使用修改后的 header 在 Ruby 中发出 HTTP GET 请求的最佳方式是什么?

我想从日志文件的末尾获取一系列字节,并一直在玩弄以下代码,但服务器返回一个响应说“这是服务器无法理解的请求”(服务器是 Apache)。

require 'net/http'
require 'uri'

#with @address, @port, @path all defined elsewhere

httpcall = Net::HTTP.new(@address, @port)

headers = {
  'Range' => 'bytes=1000-'
}

resp, data = httpcall.get2(@path, headers)
  1. 有没有更好的方法在 Ruby 中定义 header ?
  2. 有谁知道为什么这对 Apache 会失败?如果我在浏览器中访问 http://[address]:[port]/[path],我会毫无问题地获得我正在寻找的数据。

最佳答案

创建了一个对我有用的解决方案(效果很好)- 这个例子得到了一个范围偏移量:

require 'uri'
require 'net/http'

size = 1000 #the last offset (for the range header)
uri = URI("http://localhost:80/index.html")
http = Net::HTTP.new(uri.host, uri.port)
headers = {
    'Range' => "bytes=#{size}-"
}
path = uri.path.empty? ? "/" : uri.path

#test to ensure that the request will be valid - first get the head
code = http.head(path, headers).code.to_i
if (code >= 200 && code < 300) then

    #the data is available...
    http.get(uri.path, headers) do |chunk|
        #provided the data is good, print it...
        print chunk unless chunk =~ />416.+Range/
    end
end

关于ruby - 如何使用修改后的 header 制作 HTTP GET?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/587559/

相关文章:

php - 如果照片上传成功

c - 如何知道 HTTP header 部分何时结束?

ruby-on-rails - 用户 has_many 测试,测试 has_many 成绩。如何计算成绩?

linux - 如何从 perl 进行经过身份验证的 https 访问

ruby - 从 Ruby 执行 Rspec

php - http post方法是如何实现的?

html - 可以在浏览器中查看哪些文件类型(内联,无需插件)

c# - 使用 RestSharp 设置 'Content-Type' header

ruby - 使用 RVM 安装 Ruby 1.9.3 时出错

arrays - 合并 Ruby 中特定索引处的数组