gpt4 book ai didi

ruby - 为什么 Ruby Net::HTTP.get_response 和 Net::HTTP.new(uri.host).request 返回不同的东西?

转载 作者:数据小太阳 更新时间:2023-10-29 08:38:17 25 4
gpt4 key购买 nike

这 2 个请求应该有相同的结果,但第一个请求返回 200(OK),第二个请求返回 404(未找到)。这是为什么?

require 'net/http'

url = "http://readwrite.com/2013/12/04/google-compute-engine"
uri = URI(url)
Net::HTTP.get_response(uri)
#=> #<Net::HTTPOK 200 OK readbody=true>
Net::HTTP.new(uri.host).request(Net::HTTP::Get.new(url))
#=> #<Net::HTTPNotFound 404 Not Found readbody=true>

它只发生在一些 url 上。我无法弄清楚模式。这是另一个示例:http://davidduchemin.com/2014/01/towards-mastery-again/

最佳答案

首先,让我们通过使用 tcpdump 查看它们的实际 HTTP 请求来比较两者,以便我们了解可能发生的情况:

tcpdump -vvASs 0 port 80 and host www.readwrite.com
# Net::HTTP.get_response(uri)GET /2013/12/04/google-compute-engine HTTP/1.1Accept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3Accept: */*User-Agent: RubyHost: readwrite.com
# Net::HTTP.new(uri.host).request(Net::HTTP::Get.new(url))GET http://readwrite.com/2013/12/04/google-compute-engine HTTP/1.1Accept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3Accept: */*User-Agent: RubyConnection: closeHost: readwrite.com

We can see that the second request is incorrectly requesting the full URL (with hostname) as the path. This is because you’re passing url to Net::HTTP::Get.new which causes Net::HTTP::Get.new(url).path to be just what we see above: the full URL with hostname. Instead pass the URI instance (uri) to Net::HTTP::Get.new:

Net::HTTP.new(uri.host).request(Net::HTTP::Get.new(uri))
#=> #<Net::HTTPOK 200 OK readbody=true>

它的 tcpdump 现在实际上与第一个相同:

GET /2013/12/04/google-compute-engine HTTP/1.1Accept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3Accept: */*User-Agent: RubyHost: readwrite.comConnection: close

关于ruby - 为什么 Ruby Net::HTTP.get_response 和 Net::HTTP.new(uri.host).request 返回不同的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21272893/

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