我有一个url列表,我需要检查哪些url是有效的.
我使用的代码是
require 'net/http' url = 'http://mysite.com' res = Net::HTTP.get_response(URI.parse(url.to_s)) puts res.code
在这里,我可以检查一个有效url的响应代码200.我的关注是返回的’res’对象包含代码,body等等.所以我的响应(res对象)变得很重.有什么办法让我只能得到响应代码.我不需要任何其他信息.请帮忙
解决方法
我没有检查是否可以使用Net :: HTTP,但您可以使用Curb,这是用于卷曲的Ruby包装器.
看看
看看
Curl::Easy#http_head
使用Net :: HTTP,您还可以使用HTTP#head
,它使用HEAD方法从服务器请求头文件.
有关HTTP方法的信息HEAD:
9.4 HEAD
The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The Metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining Metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity,accessibility,and recent modification.
require 'net/http' response = nil Net::HTTP.start('www.example.com',80) {|http| response = http.head('/page.html') } puts response.code