You are located behind a proxy server and you want your Ruby application to access Internet resources by utilizing HTTP/HTTPs?
This recipe shows you how to cope with this problem.
Private networks often require internal applications explicitly to utilize Proxy servers. Ruby provides a build-in support for standard proxy servers with and without user authentication.
If you are reqired to support propritary proxy protocols like NTLM, there are solutions available, too. But this article cares about standard proxy-servers, only.
The following script is reading the proxy settings from the process environment.
Applications on Linux systems generally support the utilization of proxy servers by analysing the environment variable ‘http_proxy‘. It contains the proxy configuration in the following form: http://proxy_host[:proxy_port].
require 'net/http' require 'uri' # fetch setting from environment variable # set to: http://proxy_host:proxy_port http_proxy = ENV["http_proxy"] proxy = URI.parse(http_proxy) url = URI.parse('http://www.linux-support.com') res = Net::HTTP::Proxy(proxy.host, proxy.port).start( url.host, url.port) { |http| http.get('/') } puts res.body
By executing the previous script you will receive the following result (the script did request an HTML document via a proxy server configured at command line):
$ ruby http-proxy-simple.rb <html> <head> <title>Linux-Support.com Redirect</title> <meta http-equiv="refresh" content="1; url=http://www.linux-support.com/cms/" /> </head> <body> You will be redirected to the <a href="http://www.linux-support.com/cms/"> Start Page</a> of http://www.linux-support.com! </body> </html>
The following script is a more general one. If credentials have been defined, they will be utilized to connect the proxy server. If no username can be found, the communication will work without authentication.
require 'net/http' require 'uri' # fetch setting from environment variable # set to: http://user:password@proxy_host:proxy_port http_proxy = ENV["http_proxy"] proxy = URI.parse(http_proxy) proxy_user, proxy_pass = proxy.userinfo.split(/:/) if proxy.userinfo # print some details regarding the proxy configuration puts proxy_user puts proxy_pass puts proxy.userinfo puts proxy.host puts proxy.port url = URI.parse('http://www.linux-support.com') res = Net::HTTP::Proxy(proxy.host, proxy.port).start( url.host, url.port, proxy_user, proxy_pass) { |http| http.get('/') } puts res.body
Additional resources: