Dem*_*emi 15 ruby http http-headers
使用修改后的头文件在Ruby中发出HTTP GET请求的最佳方法是什么?
我希望从日志文件的末尾获取一系列字节,并且一直在使用以下代码,但是服务器正在回放一个响应,说"它是服务器无法理解的请求"(服务器是阿帕奇).
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)
Run Code Online (Sandbox Code Playgroud)
http://[address]:[port]/[path]我会得到我正在寻找的数据而没有问题.Dem*_*emi 25
创建了一个适合我的解决方案(工作得非常好) - 这个示例获得范围偏移:
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
Run Code Online (Sandbox Code Playgroud)
如果您可以访问服务器日志,请尝试将来自浏览器的请求与Ruby中的请求进行比较,看看是否能告诉您任何内容.如果这不实用,请启动Webrick作为文件服务器的模拟.不要担心结果,只需比较请求,看看他们在做什么不同.
至于Ruby样式,你可以内联移动标题,如下所示:
httpcall = Net::HTTP.new(@address, @port)
resp, data = httpcall.get2(@path, 'Range' => 'bytes=1000-')
Run Code Online (Sandbox Code Playgroud)
另请注意,在Ruby 1.8+中,您几乎肯定会运行,Net::HTTP#get2返回单个HTTPResponse对象,而不是一resp, data对.
| 归档时间: |
|
| 查看次数: |
30679 次 |
| 最近记录: |