2009-02-25 22 views
15

¿Cuál es la mejor manera de realizar una solicitud HTTP GET en Ruby con encabezados modificados?¿Cómo hacer un HTTP GET con encabezados modificados?

Quiero obtener un rango de bytes desde el final de un archivo de registro y he estado jugando con el siguiente código, pero el servidor está devolviendo una respuesta diciendo que "es una solicitud que el servidor no pudo entender" (el servidor es 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. ¿Hay una mejor manera de definir los encabezados en Ruby?
  2. ¿Alguien sabe por qué esto estaría fallando en contra de Apache? Si hago un obtener en un navegador al http://[address]:[port]/[path] obtengo los datos que estoy buscando sin problema.
+1

Encontrado esta pregunta en una búsqueda en Google ... hay tantas maneras de hacer peticiones HTTP con Ruby>. < – Nippysaurus

Respuesta

25

creado una solución que funcionó para mí (funcionaba muy bien) - este ejemplo recibiendo una compensación de rango:

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

Si tiene acceso a los registros del servidor, intente comparar la solicitud del navegador con la de Ruby y vea si eso le dice algo. Si esto no es práctico, encienda Webrick como un simulacro del servidor de archivos. No se preocupe por los resultados, simplemente compare las solicitudes para ver lo que están haciendo de manera diferente.

cuanto a estilo de Rubí, se podía mover las cabeceras de línea, así:

httpcall = Net::HTTP.new(@address, @port) 

resp, data = httpcall.get2(@path, 'Range' => 'bytes=1000-') 

Además, tenga en cuenta que en Ruby 1.8+, lo que está ejecutando casi con toda seguridad, Net::HTTP#get2 devuelve un único objeto HTTPResponse, no un resp, data par.

+0

Corriendo 1.8.7 - buena captura en el valor de retorno, gracias. – Demi