我有一个启动多个HTTP
连接的应用程序,我想为所有连接添加代理.
该应用程序使用net/HTTP
,TCP
插座,open-uri
所以我非常希望能够修补这些库,而不是手动添加它每在发起连接的代码每个位置开始的所有连接.
有没有办法实现(上Ruby 1.9.2
)?
Open URI使用HTTP_PROXY环境变量
这是一篇关于如何在windows和unix变体上使用它的文章.
http://kaamka.blogspot.com/2009/06/httpproxy-environment-variable.html
你也可以使用ENV哈希直接在ruby中设置它
ENV['HTTP_PROXY'] = 'http://username:password@hostname:port'
Run Code Online (Sandbox Code Playgroud)
net/http文档说不依赖于环境并且每次都设置它
require 'net/http'
require 'uri'
proxy_host = 'your.proxy.host'
proxy_port = 8080
uri = URI.parse(ENV['http_proxy'])
proxy_user, proxy_pass = uri.userinfo.split(/:/) if uri.userinfo
Net::HTTP::Proxy(proxy_host, proxy_port,
proxy_user, proxy_pass).start('www.example.com') {|http|
# always connect to your.proxy.addr:8080 using specified username and password
:
}
Run Code Online (Sandbox Code Playgroud)
来自http://ruby-doc.org/stdlib/libdoc/net/http/rdoc/classes/Net/HTTP.html