How to set a proxy in rubys net/http?

ada91 picture ada91 · Apr 3, 2013 · Viewed 29.2k times · Source

I'm trying to set a proxy and to use it in a simple get request like in the documentation. But I always receive an error! The adress and port are right with open-uri it worked.. it's http://proxy:8080 .

proxy_addr = 'proxy'
proxy_port = 8080

Net::HTTP.new('google.de', nil, proxy_addr, proxy_port).start { |http|
  # always proxy via your.proxy.addr:8080
  Net::HTTP.get('google.de', '')
}

What am I doing wrong? Thanks for all answers!

Answer

Mihail Davydenkov picture Mihail Davydenkov · May 21, 2014

There is another option:

Net::HTTP will automatically create a proxy from the http_proxy environment variable if it is present.

So you can use

ENV['http_proxy'] = 'http://172.16.3.160:4226' # your http://address:port here

and Net::HTTP will use it for all requests by default.

It can be helpful for net_http requests in third-party libraries (for example it works for gem gibbon for MailChimp).

Pass nil for the proxy address to disable default http_proxy.