Ruby NET::HTTP 在正文之前读取标头(没有 HEAD 请求)?

2024-01-10

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

我不想抓取流音频,例如:http://listen2.openstream.co/334 http://listen2.openstream.co/334

事实上我只想抓取Html内容,所以没有pdf、视频、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 请求。


net/http支持流式传输,您可以使用它在正文之前读取标题。

代码示例,

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Ruby NET::HTTP 在正文之前读取标头(没有 HEAD 请求)? 的相关文章

随机推荐