【问题标题】:Find the redirect-url for POST request in rest-client在 rest-client 中找到 POST 请求的重定向 URL
【发布时间】:2014-04-18 07:56:40
【问题描述】:

我需要获取我正在发出的 POST 请求的重定向 URL 名称。

begin
  RestClient.post url, :param => p
rescue => e
  e.inspect
end

回应: "302 Found: <html><body>You are being <a href=\"https://www.abcd.com/971939frwddm\">redirected</a>.</body></html>\n"

我需要的只是 uri:www.abcd.com/971939frwddm

我的问题是我是否可以直接从对象 e 获取 uri 而无需正则表达式字符串?

【问题讨论】:

    标签: ruby rest rest-client


    【解决方案1】:

    这应该是work:

    begin
      RestClient.post url, :param => p
    rescue Redirect => e
      redirected_url = e.url
    end
    

    更新
    由于以上都不起作用,我建议您尝试:

    RestClient.post(url, :param => p) do |response, request, result, &block|
      if [301, 302, 307].include? response.code
        redirected_url = response.headers[:location]
      else
        response.return!(request, result, &block)
      end
    end
    

    (这是follow redirection on all request types的建议实现和Requestfollow_redirection实现的组合

    【讨论】:

    • NoMethodError: undefined method 'url' for #<RestClient::Found:0xa534d64>e.url而来
    • 谢谢您,您可以通过RestClient::Exception => exex.response.headers[:location] 获取重定向网址。
    【解决方案2】:

    以防万一有人遇到类似情况并希望在重定向后获得最终 url,以下对我有用。

    result = RestClient.get(url, :user_agent => AGENT, :cookies => @cookies){ |response, request, result, &block|
      if [301, 302, 307].include? response.code
        response.follow_redirection(request, result, &block)
      else
        final_url = request.url
        response.return!(request, result, &block)
      end
    }
    

    final_url 将包含最终的 redirect_url

    【讨论】:

    • final_url需要事先初始化,否则只能在博客内访问,不能在外访问。一个简单的final_url = nil 有效。在 Ruby 2.1.3 中测试。
    猜你喜欢
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多