Ruby Net::HTTP - following 301 redirects

前端 未结 5 750
时光说笑
时光说笑 2020-12-05 04:36

My users submit urls (to mixes on mixcloud.com) and my app uses them to perform web requests.

A good url returns a 200 status code:

         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 05:00

    Here is the code I came up with (derived from different examples) which will bail out if there are too many redirects (note that ensure_success is optional):

    require "net/http"
    require "uri"
    class Net::HTTPResponse
      def ensure_success
        unless kind_of? Net::HTTPSuccess
          warn "Request failed with HTTP #{@code}"
          each_header do |h,v|
            warn "#{h} => #{v}"
          end
          abort
        end
      end
    end
    def do_request(uri_string)
      response = nil
      tries = 0
      loop do
        uri = URI.parse(uri_string)
        http = Net::HTTP.new(uri.host, uri.port)
        request = Net::HTTP::Get.new(uri.request_uri)
        response = http.request(request)
        uri_string = response['location'] if response['location']
        unless response.kind_of? Net::HTTPRedirection
          response.ensure_success
          break
        end
        if tries == 10
          puts "Timing out after 10 tries"
          break
        end
        tries += 1
      end
      response
    end
    

提交回复
热议问题