我使用以下代码发出请求并遵循重定向:
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代码中没有看到任何明显的内容。
如果我想知道这个,我是否需要编写自己的自定义中间件?有没有人知道那里的中间件可能会这样做?
答案 0 :(得分:2)
我找到了解决方案。您可以将回调传递给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
答案 1 :(得分:0)
实际上,我认为我刚刚根据这里的帖子找到答案:https://stackoverflow.com/a/20818142/4701287
我需要将传入的原始网址与生成的网址进行比较。从上面扩展我的例子:
original_url = 'http://www.example.com/redirect'
resp = conn.get(original_url)
was_redirected = (original_url == resp.to_hash[:url].to_s)