def net_http_request(uri, options, follows_remaining: options.fetch(:max_redirects, 2), &block)
      http, request = create_net_http(uri, options)

      begin
        response = http.start do
          http.request(request) do |response|
            unless response.is_a?(Net::HTTPRedirection)
              yield response
              # In certain cases the caller wants to download only one portion
              # of the file and close the connection, so we tell Net::HTTP that
              # it shouldn't continue retrieving it.
              response.instance_variable_set("@read", true)
            end
          end
        end
      rescue => exception
        request_error!(exception)
      end

      if response.is_a?(Net::HTTPRedirection)
        raise Down::TooManyRedirects if follows_remaining == 0

        # fail if redirect URI is not a valid http or https URL
        begin
          location = ensure_uri(response["Location"], allow_relative: true)
        rescue Down::InvalidUrl
          raise ResponseError.new("Invalid Redirect URI: #{response["Location"]}", response: response)
        end

        # handle relative redirects
        location = uri + location if location.relative?

        net_http_request(location, options, follows_remaining: follows_remaining - 1, &block)
      end
    end
def net_http_request(uri, options, follows_remaining: options.fetch(:max_redirects, 2), &block)
      http, request = create_net_http(uri, options)

      begin
        response = http.start do
          http.request(request) do |response|
            unless response.is_a?(Net::HTTPRedirection)
              yield response
              # In certain cases the caller wants to download only one portion
              # of the file and close the connection, so we tell Net::HTTP that
              # it shouldn't continue retrieving it.
              response.instance_variable_set("@read", true)
            end
          end
        end
      rescue => exception
        request_error!(exception)
      end

      if response.is_a?(Net::HTTPRedirection)
        raise Down::TooManyRedirects if follows_remaining == 0

        # fail if redirect URI is not a valid http or https URL
        begin
          location = ensure_uri(response["Location"], allow_relative: true)
        rescue Down::InvalidUrl
          raise ResponseError.new("Invalid Redirect URI: #{response["Location"]}", response: response)
        end

        # handle relative redirects
        location = uri + location if location.relative?

        net_http_request(location, options, follows_remaining: follows_remaining - 1, &block)
      end
    end
Makes a Net::HTTP request and follows redirects.