簡體   English   中英

在使用Ruby獲取主體之前,如何檢查Content-type標頭?

[英]How do I check the Content-type header before getting the body using Ruby?

我需要一種能夠獲取網頁的方式/庫,如下例所示:

result = http_client.get('/some_page.html') do |response|
  if response.content_type == 'text/html' and response.code == 200
    response.read_body #the headers are returned along with page body
  else
    #not reading the body so only the headers are returned without body
  end
end

現在,在“ text / html”頁面具有成功響應的情況下:

p result.code #>200
p result.content_type #>text/html
p result.body #><DOCTYPE html...

如果是非“ text / html”頁面或非200頁面:

p result.code #>404
p result.content_type #>text/html
p result.body #>nil

所有這些都必須在對Web服務器的一個請求中完成。 發出HTTP HEAD請求檢查標頭,然后發出HTTP GET請求獲取正文是不可接受的,因為這將導致2個請求。

哪些寶石/圖書館提供了這種可能性?

更新資料

我發現了一個深入到net / http庫的解決方案:

client.request_get(uri.request_uri) do |res|
  if res.content_type == 'text/html'
    res.read_body
  else
    res.instance_eval {@body_exist = false}
  end
end

我發現了一個深入到net / http庫的解決方案:

client.request_get(uri.request_uri) do |res|
  if res.content_type == 'text/html'
    res.read_body
  else
    res.instance_eval {@body_exist = false}
  end
end

也許HTTP HEAD返回您想要的。

應該支持HEAD,因為此鏈接建議

http://rubydoc.info/gems/httpclient/2.1.5.2/HTTPClient

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM