我在Ruby中使用Net::HTTP来抓取URL。
我不想抓取诸如:http://listen2.openstream.co/334之类的音频流
事实上,我只想抓取Html内容,所以没有pdfs,video,txt。
现在,我将open_timeout和read_timeout都设置为10,所以即使我爬行这些流式音频页面,它们也会超时。
url = 'http://listen2.openstream.co/334'
path = uri.path
req= Net::HTTP::Get.new(path, {'Accept' => '*/*', 'Content-Type' => 'text/plain; charset=utf-8', 'Connection' => 'keep-alive','Accept-Encoding' => 'Identity'})
uri = Addressable::URI.parse(url)
resp = Net::HTTP.start(uri.host, uri.inferred_port) do |httpRequest|
httpRequest.open_timeout = 10
httpRequest.read_timeout = 10
#how can I read the headers here before it's streaming the body and then exit b/c the content type is audio?
httpRequest.request(req)
end但是,有没有办法在读取http响应的正文之前检查报头,以确定它是否是音频?我想在不发送单独的HEAD请求的情况下这样做。
发布于 2016-12-24 04:08:21
net/http支持流式传输,您可以使用它来读取body之前的header。
代码示例
url = URI('http://stackoverflow.com/questions/41306082/ruby-nethttp-read-the-header-before-the-body-without-head-request')
Net::HTTP.start(url.host, url.port) do |http|
request = Net::HTTP::Get.new(url)
http.request(request) do |response|
# check headers here, body has not yet been read
# then call read_body or just body to read the body
if true
response.read_body do |chunk|
# process body chunks here
end
end
end
end发布于 2018-01-11 04:36:53
我将在今晚晚些时候添加一个ruby示例。然而,为了快速响应。有一个简单的技巧可以做到这一点。
您可以使用HTTP Range标头来指示是否要从服务器接收哪个范围的字节。下面是一个示例:
curl -XGET http://www.sample-videos.com/audio/mp3/crowd-cheering.mp3 -v -H "Range: bytes=0-1"上面的例子意味着服务器将返回0到1字节范围内的数据。
发布于 2016-12-24 03:11:54
由于我没有找到在Net::HTTP中正确执行此操作的方法,而且我看到您已经将addressable gem用作外部依赖项,因此这里有一个使用非常棒的http gem的解决方案
require 'http'
response = HTTP.get('http://listen2.openstream.co/334')
# Here are the headers
puts response.headers
# Everything ok? Start streaming the response
body = response.body
body.stream!
# now just call `readpartial` on the body until it returns `nil`
# or some other break condition is met如果你被要求使用Net::HTTP,很抱歉,希望其他人能找到答案。在这种情况下,单独的HEAD请求可能确实是可行的。
https://stackoverflow.com/questions/41306082
复制相似问题