2009-02-25 56 views
15

在帶有修改頭的Ruby中進行HTTP GET請求的最佳方式是什麼?如何使用修改的標頭進行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) 
  1. 有沒有更好的方法在Ruby中定義頁眉?
  2. 有誰知道爲什麼這會對Apache失敗?如果我在瀏覽器中訪問http://[address]:[port]/[path],我可以毫無問題地獲得我正在尋找的數據。
+1

發現在谷歌搜索這個問題......有這麼多的方式做HTTP請求Ruby>。< – Nippysaurus 2009-07-25 06:20:51

回答

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 
6

如果您有權訪問服務器日誌,請嘗試將來自瀏覽器的請求與來自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對。

+0

運行1.8.7 - 很好的捕獲返回值,謝謝。 – Demi 2009-02-25 20:26:47