Ruby - net/http - following redirects

后端 未结 6 1056
北恋
北恋 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:19

    Given a URL that redirects

    url = 'http://httpbin.org/redirect-to?url=http%3A%2F%2Fhttpbin.org%2Fredirect-to%3Furl%3Dhttp%3A%2F%2Fexample.org'
    

    A. Net::HTTP

    begin
      response = Net::HTTP.get_response(URI.parse(url))
      url = response['location']
    end while response.is_a?(Net::HTTPRedirection)
    

    Make sure that you handle the case when there are too many redirects.

    B. OpenURI

    open(url).read
    

    OpenURI::OpenRead#open follows redirects by default, but it doesn't limit the number of redirects.

提交回复
热议问题