Ruby HTTP Proxy snippet

This post was written on 2006/06/17 at 20:11:37 by Horst Gutmann

Just a small pattern is use all the time for writing HTTP requests that work

with an without a proxy.

#!/usr/bin/env ruby

require 'net/http'

require 'ostruct'



proxy = ENV['http_proxy'] ? URI.parse(ENV['http_proxy']) : OpenStruct.new

Net::HTTP::Proxy(proxy.host,proxy.port,proxy.user,proxy.password).start('www.apple.com') do |http|

puts http.get('/').body

end

I use here the OpenStruct class which actually works like a more generic Struct where fields can added at will. Comes quite handy since You normally want to have "host", "port", "username" and "password" accessors for your proxy URL and Net::HTTP::Proxy is kind enough to accept nil values if they are not required :)

Comments:

  • Anonymous (Guest)

    that's nice but if you use proxys you should consider to make a timeout if the proxy went down

    June 26, 2007, 2:15 p.m.

  • John Ward (Guest)

    Nice snippet, had an issue with mechanize.

    Interestingly your snippet works using Http directly, but fails when I try to use it with set_proxy of mechanize.

    Feb. 8, 2008, 1:23 p.m.

*'d input fields are required.