【问题标题】:How to make an HTTP GET with modified headers?如何使用修改后的标头制作 HTTP GET?
【发布时间】:2010-10-09 21:49:19
【问题描述】:

在 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 中定义标头?
  2. 有谁知道为什么这对 Apache 会失败?如果我在浏览器中访问http://[address]:[port]/[path],我会毫无问题地获得我正在寻找的数据。

【问题讨论】:

  • 在 google 搜索中发现了这个问题......使用 Ruby 进行 HTTP 请求的方法有很多>。

标签: ruby http http-headers


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    如果您有权访问服务器日志,请尝试将来自浏览器的请求与来自 Ruby 的请求进行比较,看看是否能告诉您任何信息。如果这不切实际,请启动 Webrick 作为文件服务器的模拟。不用担心结果,只需比较请求,看看它们在做什么不同。

    对于 Ruby 样式,您可以将标题内联移动,如下所示:

    httpcall = Net::HTTP.new(@address, @port)
    
    resp, data = httpcall.get2(@path, 'Range' => 'bytes=1000-')
    

    另外,请注意,在 Ruby 1.8+ 中,您几乎可以肯定正在运行的 Net::HTTP#get2 返回单个 HTTPResponse 对象,而不是 resp, data 对。

    【讨论】:

      猜你喜欢
      • 2011-09-01
      • 2011-04-27
      • 1970-01-01
      • 2017-09-14
      • 1970-01-01
      • 2018-05-12
      • 1970-01-01
      • 2016-07-30
      • 1970-01-01
      相关资源
      最近更新 更多