-
Notifications
You must be signed in to change notification settings - Fork 163
/
proxy.rb
42 lines (28 loc) · 1.33 KB
/
proxy.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
require 'net/http'
require 'uri'
uri = URI.parse('http://google.com')
# Net::HTTP will automatically create a proxy from the http_proxy environment variable if it is present.
ENV['http_proxy'] # => "http://myproxy.com:8080"
http = Net::HTTP.new(uri.host, uri.port)
# This request uses proxy.
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
# But it does not work without a Net::HTTP object.
# This request doest not use proxy.
response = Net::HTTP.get_response(uri)
# You can pass proxy address to Net::HTTP constructor too.
proxy_uri = URI.parse('http://myproxy.com:8080')
http = Net::HTTP.new(uri.host, uri.port, proxy_uri.host, proxy_uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
# If you are using an authenticated proxy, use Net::HTTP.start method.
Net::HTTP.start(uri.host, uri.port, proxy_uri.host, proxy_uri.port, 'proxy_user', 'proxy_pass') do |http|
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
end
# If you want to reuse Net::HTTP instance, don't forget to finish HTTP connection.
http = Net::HTTP.start(uri.host, uri.port, proxy_uri.host, proxy_uri.port, 'proxy_user', 'proxy_pass').start
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
# Finish HTTP connection.
http.finish if http.started?