首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ruby NET::HTTP读取body之前的header (没有HEAD请求)?

Ruby NET::HTTP读取body之前的header (没有HEAD请求)?
EN

Stack Overflow用户
提问于 2016-12-24 02:14:21
回答 4查看 1.7K关注 0票数 9

我在Ruby中使用Net::HTTP来抓取URL。

我不想抓取诸如:http://listen2.openstream.co/334之类的音频流

事实上,我只想抓取Html内容,所以没有pdfs,video,txt。

现在,我将open_timeout和read_timeout都设置为10,所以即使我爬行这些流式音频页面,它们也会超时。

代码语言:javascript
复制
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请求的情况下这样做。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-12-24 04:08:21

net/http支持流式传输,您可以使用它来读取body之前的header。

代码示例

代码语言:javascript
复制
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
票数 6
EN

Stack Overflow用户

发布于 2018-01-11 04:36:53

我将在今晚晚些时候添加一个ruby示例。然而,为了快速响应。有一个简单的技巧可以做到这一点。

您可以使用HTTP Range标头来指示是否要从服务器接收哪个范围的字节。下面是一个示例:

代码语言:javascript
复制
curl -XGET http://www.sample-videos.com/audio/mp3/crowd-cheering.mp3 -v -H "Range: bytes=0-1"

上面的例子意味着服务器将返回0到1字节范围内的数据。

请参阅:https://developer.mozilla.org/en-US/docs/Web/HTTP/Range

票数 1
EN

Stack Overflow用户

发布于 2016-12-24 03:11:54

由于我没有找到在Net::HTTP中正确执行此操作的方法,而且我看到您已经将addressable gem用作外部依赖项,因此这里有一个使用非常棒的http gem的解决方案

代码语言:javascript
复制
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请求可能确实是可行的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41306082

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档