How to download via HTTP only piece of big file with ruby

后端 未结 3 1833
误落风尘
误落风尘 2020-12-06 07:45

I only need to download the first few kilobytes of a file via HTTP.

I tried

require \'open-uri\'
url = \'http://example.com/big-file.dat\'
file = ope         


        
3条回答
  •  天命终不由人
    2020-12-06 08:44

    This seems to work when using sockets:

    require 'socket'                  
    host = "download.thinkbroadband.com"                 
    path = "/1GB.zip" # get 1gb sample file
    request = "GET #{path} HTTP/1.0\r\n\r\n"
    socket = TCPSocket.open(host,80) 
    socket.print(request)        
    
    # find beginning of response body
    buffer = ""                    
    while !buffer.match("\r\n\r\n") do
      buffer += socket.read(1)  
    end           
    
    response = socket.read(100) #read first 100 bytes of body
    puts response
    

    I'm curious if there is a "ruby way".

提交回复
热议问题