11

I have an application that initiates multiple HTTP connections and I would like to add a proxy to all connections.

The application is using net/HTTP, TCP sockets and open-uri so ideally I would like to be able to patch all connections initiated from those libraries instead of adding it manually to each and every location in the code that initiates a connection.

Is there a way to accomplish that (on Ruby 1.9.2)?

2 Answers 2

7

Open URI uses the HTTP_PROXY environment variable

Here is an article on how to use it on both windows and unix variants.

http://kaamka.blogspot.com/2009/06/httpproxy-environment-variable.html

you can also set it directly in ruby using the ENV hash

ENV['HTTP_PROXY'] = 'http://username:password@hostname:port'

the net/http documentation says not to rely on the environment and set it each time

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
        :
}

from http://ruby-doc.org/stdlib/libdoc/net/http/rdoc/classes/Net/HTTP.html

Sign up to request clarification or add additional context in comments.

1 Comment

Ow this saved my day!!! ENV['HTTP_PROXY'] = '<ip_of_the_proxy>:3128' and then I can finally connect to a remote selenium-grid.
2

Yes and mechanize does too (this is for the 1.0.0 verison)

require 'mechanize'
url = 'http://www.example.com'

agent = Mechanize.new
agent.user_agent_alias = 'Mac Safari'
agent.set_proxy('127.0.0.1', '3128')
@page = agent.get(:url => url)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.