【问题标题】:Net::HTTP Proxy listNet::HTTP 代理列表
【发布时间】:2014-11-30 21:19:34
【问题描述】:

我知道您可以在 ruby​​ Net::HTTP 中使用代理。但是,我不知道如何使用一堆代理来做到这一点。我需要 Net::HTTP 更改为另一个代理并在每次发布请求后发送另一个发布请求。另外,如果以前的代理不起作用,是否可以让 Net::HTTP 更改为另一个代理?如果是这样,怎么做? 我正在尝试在以下代码中实现脚本的代码:

require 'net/http'
sleep(8)
http = Net::HTTP.new('URLHERE', 80)
http.read_timeout = 5000
http.use_ssl = false
path = 'PATHHERE'
data = '(DATAHERE)'
headers = {
'Referer' => 'REFERER HERE',
'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8',
'User-Agent' => '(USERAGENTHERE)'}

resp, data = http.post(path, data, headers)


# Output on the screen -> we should get either a 302 redirect (after a successful login) or an error page
puts 'Code = ' + resp.code
puts 'Message = ' + resp.message
resp.each {|key, val| puts key + ' = ' + val}
puts data

结束

【问题讨论】:

  • 您是否能够仅使用一个代理使其工作?如果是这样,你会发布代码吗?
  • 我一直无法成功实现代理。

标签: ruby proxy net-http


【解决方案1】:

给定一个代理数组,以下示例将通过数组中的每个代理发出请求,直到收到“302 Found”响应。 (这实际上不是一个工作示例,因为 Google 不接受 POST 请求,但如果您插入自己的目的地和工作代理,它应该可以工作。)

require 'net/http'

destination = URI.parse "http://www.google.com/search"
proxies = [
    "http://proxy-example-1.net:8080",
    "http://proxy-example-2.net:8080",
    "http://proxy-example-3.net:8080"
]

# Create your POST request_object once
request_object = Net::HTTP::Post.new(destination.request_uri)
request_object.set_form_data({"q" => "stack overflow"})

proxies.each do |raw_proxy|

    proxy = URI.parse raw_proxy

    # Create a new http_object for each new proxy
    http_object = Net::HTTP.new(destination.host, destination.port, proxy.host, proxy.port)

    # Make the request
    response = http_object.request(request_object)

    # If we get a 302, report it and break
    if response.code == "302"
        puts "#{proxy.host}:#{proxy.port} responded with #{response.code} #{response.message}"
        break
    end
end

您可能还应该在每次发出请求时使用begin ... rescue ... end 进行一些错误检查。如果您不进行任何错误检查并且代理已关闭,则控制将永远不会到达检查response.code == "302" 的行——程序将失败并出现某种类型的连接超时错误。

有关可用于自定义 Net::HTTP::Post 对象的其他方法,请参阅 the Net::HTTPHeader docs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2021-12-29
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    相关资源
    最近更新 更多