Ruby - net/http - following redirects

后端 未结 6 1055
北恋
北恋 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条回答
  •  旧时难觅i
    2020-12-01 03:38

    If you do not need to care about the details at each redirection, you can use the library Mechanize

    require 'mechanize'
    
    agent = Mechanize.new
    begin
        response = @agent.get(url)
    rescue Mechanize::ResponseCodeError
        // response codes other than 200, 301, or 302
    rescue Timeout::Error
    rescue Mechanize::RedirectLimitReachedError
    rescue StandardError
    end
    

    It will return the destination page. Or you can turn off redirection by this :

    agent.redirect_ok = false
    

    Or you can optionally change some settings at the request

    agent.user_agent = "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Mobile Safari/537.36"
    

提交回复
热议问题