加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何仅获取Ruby中HTTP请求的响应代码

发布时间:2020-12-16 21:38:39 所属栏目:百科 来源:网络整理
导读:我有一个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’对象包含代
我有一个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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读