2009-07-13 6 views

답변

4

이 소켓을 사용하는 경우 작동하는 것 같다 :

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 

는 "루비 방법 '이 있다면 궁금 해요.

+0

안녕하세요 미셸, 나는 그런 '와 같은 파일을 시도 할 때마다 어떤 이유로 HTTP :// www.forcefieldpr.com/asdyoucantbealone.mp3'는 브라우저에서 작동하며 404 html 페이지가 계속 표시됩니다. 이 요청과 관련이 있습니까? –

+0

@AaronMoodie의 문제점을 수정 한 편집을 제출했습니다. 어떤 웹 서버는 "Host"헤더가 필요하므로'request = "GET # {path} HTTP/1.1 \ r \ nHost : # {host} \ r \ n \ r \ n" – inket

0

"OpenURI returns two different objects"을 확인하십시오. 미리 설정된 한계 값을 초과 한 후 다운로드를 중단하거나 나머지 결과를 버리는 방법을 남용 할 수 있습니다.

+0

감사를 – taro

3

이것은 오래된 글이지만 여전히 내 연구에 따르면 답이 거의없는 것 같습니다.

require 'net/http' 

# provide access to the actual socket 
class Net::HTTPResponse 
    attr_reader :socket 
end 

uri = URI("http://www.example.com/path/to/file") 
begin 
    Net::HTTP.start(uri.host, uri.port) do |http| 
    request = Net::HTTP::Get.new(uri.request_uri) 
    # calling request with a block prevents body from being read 
    http.request(request) do |response| 
     # do whatever limited reading you want to do with the socket 
     x = response.socket.read(100); 
    end 
    end 
rescue IOError 
    # ignore 
end 

이동 백업하면 조기에 HTTP.finish를 호출 할 때 발생 년대 IO 오류를 잡아 : 여기 원숭이 패치 순 :: HTTP 비트에 의해 내가 생각 해낸 해결책이다.

참고는 HTTPResponse 객체 내 소켓 진정한 IO 객체 (이 BufferedIO라는 내부 클래스의)은 아니지만, 너무, 당신이 필요로하는 IO 방법을 모방, 원숭이 패치 꽤 간단합니다. 예를 들어, 내가 (exifr)를 사용하고 다른 라이브러리를 쉽게했다 readchar 방법을 추가 할 필요가 : 흥미로운 지점에 대한

class Net::BufferedIO 
    def readchar 
    read(1)[0].ord 
    end 
end 
+0

그레이트! 'response.instance_variable_get (: @ socket) .read (5120)' – inket

+0

이 솔루션은 OS X 10.9에서 ruby-2.0.0p247로 무한정 멈추게됩니다. 문제를 줄이지는 못했지만 backtrace는'net/protocol.rb'에서 155 행을 언급합니다. – inket

관련 문제