代码之家  ›  专栏  ›  技术社区  ›  Demi

如何使用修改的头创建HTTP GET?

  •  15
  • Demi  · 技术社区  · 15 年前

    在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)
    
    1. 有没有更好的方法在Ruby中定义标题?
    2. 有人知道为什么这会对Apache失败吗?如果我在浏览器中进行访问 http://[address]:[port]/[path] 我得到的数据,我正在寻找没有问题。
    2 回复  |  直到 12 年前
        1
  •  25
  •   Demi    15 年前

    创建了一个适合我的解决方案(效果非常好)-此示例获取范围偏移:

    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
  •  6
  •   the Tin Man    12 年前

    如果您可以访问服务器日志,请尝试将来自浏览器的请求与来自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 一对