2

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

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如果遵循了重定向,则设置为trueif 或如果没有遵循重定向,则设置为 false 之类的东西?

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

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

4

2 回答 2

3

我找到了解决方案。您可以将回调传递给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
于 2018-12-04T20:02:25.467 回答
-1

实际上,我想我只是根据这里的帖子找到了答案:https ://stackoverflow.com/a/20818142/4701287

我需要将我传入的原始 url 与生成的 url 进行比较。从上面扩展我的示例:

original_url = 'http://www.example.com/redirect'
resp = conn.get(original_url)
was_redirected = (original_url == resp.to_hash[:url].to_s)
于 2015-04-16T18:45:04.223 回答