Ruby - net/http -以下重定向

ut6juiuv  于 2022-12-18  发布在  Ruby
关注(0)|答案(6)|浏览(118)

我有一个URL,我使用HTTPGET将一个查询传递沿着一个页面,最新版本(net/http)的情况是脚本不会超出302响应。HTTP客户端、net/http、Rest-Client、客户端、用户端、服务器端...
我需要一种方法来继续到最后一页,以验证该页html的属性标记。重定向是由于移动的用户代理命中一个页面,重定向到移动视图,因此移动用户代理在头。下面是我的代码,因为它是今天:

require 'uri'
require 'net/http'

class Check_Get_Page

    def more_http
        url = URI.parse('my_url')
        req, data = Net::HTTP::Get.new(url.path, {
        'User-Agent' => 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5'
        })
        res = Net::HTTP.start(url.host, url.port) {|http|
        http.request(req)
            }
        cookie = res.response['set-cookie']
        puts 'Body = ' + res.body
        puts 'Message = ' + res.message
        puts 'Code = ' + res.code
        puts "Cookie \n" + cookie
    end

end

m = Check_Get_Page.new
m.more_http

任何建议将不胜感激!

mutmk8jj

mutmk8jj1#

要跟踪重定向,您可以执行如下操作(taken from ruby-doc

重定向后

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/')
hmae6n7t

hmae6n7t2#

给定重定向的URL

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)

当有太多的重定向时,请确保您处理这种情况。
B. OpenURI

open(url).read


OpenURI::OpenRead#open默认情况下遵循重定向,但不限制重定向的次数。

vzgqcmou

vzgqcmou3#

我写了另一个类,基于这里给出的例子,非常感谢大家。我添加了cookie,参数和异常,最后得到了我需要的:https://gist.github.com/sekrett/7dd4177d6c87cf8265cd

require 'uri'
require 'net/http'
require 'openssl'

class UrlResolver
  def self.resolve(uri_str, agent = 'curl/7.43.0', max_attempts = 10, timeout = 10)
    attempts = 0
    cookie = nil

    until attempts >= max_attempts
      attempts += 1

      url = URI.parse(uri_str)
      http = Net::HTTP.new(url.host, url.port)
      http.open_timeout = timeout
      http.read_timeout = timeout
      path = url.path
      path = '/' if path == ''
      path += '?' + url.query unless url.query.nil?

      params = { 'User-Agent' => agent, 'Accept' => '*/*' }
      params['Cookie'] = cookie unless cookie.nil?
      request = Net::HTTP::Get.new(path, params)

      if url.instance_of?(URI::HTTPS)
        http.use_ssl = true
        http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      end
      response = http.request(request)

      case response
        when Net::HTTPSuccess then
          break
        when Net::HTTPRedirection then
          location = response['Location']
          cookie = response['Set-Cookie']
          new_uri = URI.parse(location)
          uri_str = if new_uri.relative?
                      url + location
                    else
                      new_uri.to_s
                    end
        else
          raise 'Unexpected response: ' + response.inspect
      end

    end
    raise 'Too many http redirects' if attempts == max_attempts

    uri_str
    # response.body
  end
end

puts UrlResolver.resolve('http://www.ruby-lang.org')
7lrncoxx

7lrncoxx4#

对我有用的参考资料如下:http://shadow-file.blogspot.co.uk/2009/03/handling-http-redirection-in-ruby.html
与大多数示例(包括这里的公认答案)相比,它更健壮,因为它处理的URL只是一个域(http://example.com-需要添加一个/),专门处理SSL,以及相对URL。
当然,在大多数情况下,使用RESTClient这样的库会更好,但有时底层细节是必要的。

3zwjbxry

3zwjbxry5#

也许你可以在这里使用curb-fu gem https://github.com/gdi/curb-fu,唯一的问题是一些额外的代码,使它跟随重定向。我以前用过下面的代码。希望它能有所帮助。

require 'rubygems'
require 'curb-fu'

module CurbFu
  class Request
    module Base
      def new_meth(url_params, query_params = {})
        curb = old_meth url_params, query_params
        curb.follow_location = true
        curb
      end

      alias :old_meth :build
      alias :build :new_meth
    end
  end
end

#this should follow the redirect because we instruct
#Curb.follow_location = true
print CurbFu.get('http://<your path>/').body
brqmpdu1

brqmpdu16#

如果不需要关心每次重定向时的详细信息,可以使用库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

它将返回目标页面。或者您可以通过以下方式关闭重定向:

agent.redirect_ok = false

或者,您也可以根据请求更改某些设置

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"

相关问题