Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a proxy in rubys net/http?

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!

like image 747
ada91 Avatar asked Apr 03 '13 16:04

ada91


3 Answers

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.

like image 108
Mihail Davydenkov Avatar answered Nov 13 '22 14:11

Mihail Davydenkov


Net::HTTP.new('google.de', nil, proxy_addr, proxy_port).start { |http|

This will create an http object for you to use in the block. Use that rather than generating new ones each time, here Net::HTTP.get('google.de', '')

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
  http.get('google.de', '')
}
like image 30
Joe Frambach Avatar answered Nov 13 '22 12:11

Joe Frambach


Here is the code that works if you are making a REST api call behind a proxy:

require "uri"
require 'net/http'
    
proxy_host = '<proxy addr>'
proxy_port = '<proxy_port'
proxy_user = '<username>'
proxy_pass = '<password>'
    
uri   = URI.parse("https://saucelabs.com:80/rest/v1/users/<username>")
proxy = Net::HTTP::Proxy(proxy_host,
                         proxy_port,
                         proxy_user,
                         proxy_pass)
    
req = Net::HTTP::Get.new(uri.path)

req.basic_auth(<sauce_username>,
               <sauce_password>)
    
result = proxy.start(uri.host,uri.port) do |http|
  http.request(req)
end
    
puts result.body
like image 12
machzqcq Avatar answered Nov 13 '22 13:11

machzqcq