gpt4 book ai didi

ruby - 法拉第中间件知道什么时候被重定向

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

我正在使用以下代码发出请求并遵循重定向:

require 'faraday'
require 'faraday_middleware'
conn = Faraday.new() do |f|
f.use FaradayMiddleware::FollowRedirects, limit: 5
f.adapter Faraday.default_adapter
end
resp = conn.get('http://www.example.com/redirect')
resp.status

此代码输出 200,因为它遵循了重定向,这很棒。但是有没有办法知道重定向是否存在?类似于 resp.redirected 如果遵循重定向则设置为 true 或者如果没有遵循重定向则设置为 false?

我在 FollowRedirects 中没有看到任何明显的东西代码。

如果我想知道这个,是否需要编写自己的自定义中间件?有谁知道可能已经做到这一点的中间件了吗?

最佳答案

我找到了一个解决方案。您可以将回调传递给 FaradayMiddleware::FollowRedirects。回调应该存在于 FollowRedirects 采用第二个参数的哈希中。由于我们必须为中间件使用 use 函数,您可以将哈希作为第二个参数传递给该函数。

  redirects_opts = {}

# Callback function for FaradayMiddleware::FollowRedirects
# will only be called if redirected to another url
redirects_opts[:callback] = proc do |old_response, new_response|

# you can pull the new redirected URL with this line of code.
# since you have access to the new url you can make a variable or
# instance vairable to keep track of the current URL

puts 'new url', new_response.url
end

@base_client = Faraday.new(url: url, ssl: { verify: true, verify_mode: 0 }) do |c|
c.request :multipart
c.request :url_encoded
c.response :json, content_type: /\bjson$/
c.use FaradayMiddleware::FollowRedirects, redirects_opts //<- pass hash here
c.adapter Faraday.default_adapter
end

关于ruby - 法拉第中间件知道什么时候被重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29666623/

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