gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:45:29 26 4
gpt4 key购买 nike

我有一个 url 列表,我需要检查以下哪些 url 是有效的。

我使用的代码是

require 'net/http'

url = 'http://mysite.com'
res = Net::HTTP.get_response(URI.parse(url.to_s))
puts res.code

在这里,我可以检查响应代码 200 以获取有效的 url。我担心返回的“res”对象包含代码、正文等。因此我的响应(res 对象)变得很重。有什么办法让我只能得到响应代码。我不需要任何其他信息。请帮忙

最佳答案

我没有检查是否可以使用 Net::HTTP,但您可以使用 Curb,它是 curl 的 Ruby 包装器。看Curl::Easy#http_head

对于 Net::HTTP,您还可以使用 HTTP#head ,它使用 HEAD 方法从服务器请求 header 。

关于 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.

关于ruby - 如何仅从 Ruby 中的 HTTP 请求获取响应代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9699755/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com