Ruby Net::HTTP Proxy Setup
Net::HTTP is Ruby's built-in HTTP client — no gems required. Its `Proxy` class method creates a proxy-aware HTTP class that routes all requests through the specified gateway. For simple proxy needs in Ruby applications, Net::HTTP is the zero-dependency option.
Basic Configuration
require 'net/http'proxy_host = 'gate.hexproxies.com' proxy_port = 8080 proxy_user = ENV['PROXY_USER'] proxy_pass = ENV['PROXY_PASS']
uri = URI('https://httpbin.org/ip')
# Create proxy-aware HTTP class proxy_class = Net::HTTP::Proxy(proxy_host, proxy_port, proxy_user, proxy_pass)
# Use the proxy class to make requests proxy_class.start(uri.host, uri.port, use_ssl: true) do |http| http.open_timeout = 15 http.read_timeout = 30
request = Net::HTTP::Get.new(uri) request['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)' request['Accept-Language'] = 'en-US,en;q=0.9'
response = http.request(request) puts "[#{response.code}] #{response.body}" end ```
Reusable Proxy Fetch Method
def fetch_via_proxy(url, max_retries: 3)
uri = URI(url)
proxy_class = Net::HTTP::Proxy(
'gate.hexproxies.com', 8080,
ENV['PROXY_USER'], ENV['PROXY_PASS']retries = 0 begin proxy_class.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http| http.open_timeout = 15 http.read_timeout = 30 response = http.request(Net::HTTP::Get.new(uri))
if [403, 429, 503].include?(response.code.to_i) && retries < max_retries retries += 1 sleep(retries * 2) raise "Retry on #{response.code}" end
return response end rescue => e retry if retries < max_retries raise e end end
response = fetch_via_proxy('https://example.com') puts response.body ```
Geo-Targeted Requests
Append a country code to the proxy username for geo-targeting:
geo_user = "#{ENV['PROXY_USER']}-country-gb"
proxy_class = Net::HTTP::Proxy('gate.hexproxies.com', 8080, geo_user, ENV['PROXY_PASS'])Common Pitfalls
Net::HTTP defaults to no timeout — requests through an unresponsive proxy will hang indefinitely. Always set `open_timeout` (for the proxy connection handshake) and `read_timeout` (for response data) explicitly. Another common issue: forgetting `use_ssl: true` for HTTPS targets causes the request to fail silently or return garbled data.
Net::HTTP::Proxy creates a new class, not an instance. Call `.start()` or `.new()` on the returned class to create connections. Each connection goes through the proxy with the configured credentials.
When to Use Net::HTTP vs Gems
Net::HTTP works for basic proxy needs without adding dependencies. For higher concurrency, use Typhoeus (libcurl-based parallelism). For stateful browsing with forms and cookies, use Mechanize. For middleware-based HTTP pipelines, use Faraday.