[英]Get URL headers without the HTML
有點奇怪的問題。 有沒有辦法讓Web服務器僅返回標頭而不返回HTML本身?
我想問一個服務器一個URL,看看它是否有效(不是404/500 / etc),並按照重定向(如果存在)進行操作,但沒有得到實際的HTML內容。
謝謝
使用HEAD而不是GET或POST
根據建議,檢查Net :: HTTP庫。
require 'net/http'
Net::HTTP.new('www.twitter.com').request_head('/').class
這正是HEAD HTTP方法所做的。
對於Ruby,有一個漂亮的寶石,它比允許執行HEAD請求的低級net / http簡單得多。
gem install rest-open-uri
然后
irb> require 'rubygems' => true irb> require 'rest-open-uri' => true irb> sio = open("http://stackoverflow.com", :method => :head) => # irb> sio.meta => {"expires"=>"Tue, 30 Nov 2010 18:08:47 GMT", "last-modified"=>"Tue, 30 Nov 2010 18:07:47 GMT", "content-type"=>"text/html; charset=utf-8", "date"=>"Tue, 30 Nov 2010 18:08:27 GMT", "content-length"=>"193779", "cache-control"=>"public, max-age=18", "vary"=>"*"} irb> sio.status => ["200", "OK"]
它遵循重定向。 如果主機不存在,則必須挽救SocketError;如果文件不存在,則必須挽救OpenURI :: HTTPError。
實際上,我不得不將pantulis的答案折疊成我自己的答案。 好像有兩種URL都不是FNS單獨工作的,所以我做到了
module URI
def self.online?(uri)
URI.exists?(uri)
end
def self.exists?(uri)
URI.exists_ver1?(uri)
end
def self.exists_ver1?(url)
@url = url
["http://", "https://"].each do |prefix|
url = url.gsub(prefix, "")
end
begin
code = Net::HTTP.new(url).request_head('/').code
[2,3].include?(code.to_i/100)
rescue
URI.exists_ver2?(@url)
end
end
def self.exists_ver2?(url)
url = "http://#{url}" if URI.parse(url).scheme.nil?
return false unless URI.is_a?(url)
uri = URI(url)
begin
request = Net::HTTP.new uri.host
response= request.request_head uri.path
#http status code 200s and 300s are ok, everything else is an error
[2,3].include? response.code.to_i/100
rescue
false
end
end
end
使用Mak提到的Ruby的net / http和HEAD方法。 從命令行檢查ri Net::HTTP#head
以獲取信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.