使用修改后的 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)
- 有没有更好的方法在 Ruby 中定义 header ?
- 有谁知道为什么这对 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/