Ruby - net/http - following redirects

后端 未结 6 1044
北恋
北恋 2020-12-01 03:05

I\'ve got a URL and I\'m using HTTP GET to pass a query along to a page. What happens with the most recent flavor (in net/http) is that the script doesn\'t go

6条回答
  •  执笔经年
    2020-12-01 03:21

    To follow redirects, you can do something like this (taken from ruby-doc)

    Following Redirection

    require 'net/http'
    require 'uri'
    
    def fetch(uri_str, limit = 10)
      # You should choose better exception.
      raise ArgumentError, 'HTTP redirect too deep' if limit == 0
    
      url = URI.parse(uri_str)
      req = Net::HTTP::Get.new(url.path, { 'User-Agent' => 'Mozilla/5.0 (etc...)' })
      response = Net::HTTP.start(url.host, url.port, use_ssl: true) { |http| http.request(req) }
      case response
      when Net::HTTPSuccess     then response
      when Net::HTTPRedirection then fetch(response['location'], limit - 1)
      else
        response.error!
      end
    end
    
    print fetch('http://www.ruby-lang.org/')
    

提交回复
热议问题