How to make an HTTP GET with modified headers?

后端 未结 2 1967
执念已碎
执念已碎 2020-12-01 09:46

What is the best way to make an HTTP GET request in Ruby with modified headers?

I want to get a range of bytes from the end of a log file and have been toying with t

2条回答
  •  感动是毒
    2020-12-01 10:29

    Created a solution that worked for me (worked very well) - this example getting a range offset:

    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
    

提交回复
热议问题