【问题标题】:Ruby HTTParty - get the redirected URLRuby HTTParty - 获取重定向的 URL
【发布时间】:2015-12-20 08:04:24
【问题描述】:

我正在尝试使用带有一些参数的 HTTParty 发送 HTTP 请求,

例如:

GET URL: http://example1.com?a=123&b=456

response_to_get = HTTParty.get('http://example1.com?a=123&b=456')

此特定请求的 redirect_urlhttp://example2.com

当我在浏览器中尝试 URL http://example1.com?a=123&b=456 时,它会重定向到预期的 URL,并像 http://example2.com?c=123trt58 一样附加参数值,但是当我使用 HTTParty 执行此操作时,我只得到一个 HTML 响应。

我的要求是从响应中获取 URL(http://example2.com?c=123trt58)。

提前致谢。

【问题讨论】:

    标签: http ruby-on-rails-4 httparty ruby-2.2


    【解决方案1】:

    你可以试试 ruby​​ gem final_redirect_url

    【讨论】:

      【解决方案2】:

      稍微更正@High6 答案:

          res = HTTParty.head("example1.com?a=123&b=456")
          res.request.last_uri.to_s
      

      这将阻止大型响应下载。只需阅读标题。

      【讨论】:

        【解决方案3】:
        require 'uri'
        require 'net/http'
        
        url = URI("https://<whatever>")
        
        req = Net::HTTP::Get.new(url)
        res = Net::HTTP.start(url.host, url.port, :use_ssl => true) {|http|
          http.request(req)
        }
        
        res['location']
        

        PS:这是使用原生 ruby​​ HTTP 库。

        【讨论】:

          【解决方案4】:

          如果您不想跟踪重定向,但仍想知道页面重定向到的位置(例如对网络爬虫很有用),您可以使用response.headers['location']

          response = HTTParty.get('http://httpstat.us/301', follow_redirects: false)
          
          if response.code >= 300 && response.code < 400
              redirect_url = response.headers['location']
          end
          

          【讨论】:

            【解决方案5】:

            要在使用HTTParty 进行重定向后获取最终 URL,您可以使用:

            res = HTTParty.get("http://example1.com?a=123&b=456")
            res.request.last_uri.to_s
            
            # response should be 'http://example2.com?c=123trt58'
            

            【讨论】:

            • 正确的选择是 res = HTTParty.head("example1.com?a=123&b=456") HTTParty.get 将下载所有内容,即使是 100Mb 的视频文件。
            • @AivilsŠtoss 您应该将其发布为答案
            猜你喜欢
            • 2011-08-17
            • 1970-01-01
            • 2013-09-07
            • 1970-01-01
            • 2013-02-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多