Differences

This shows you the differences between two versions of the page.

Link to this comparison view

ruby_net_http_request_with_proxy [2017/09/05 12:18] (current)
Line 1: Line 1:
 +====== Ruby net http request with proxy ======
  
 +Here is a Ruby Module to handle the net http request using proxy, if you want only to use the module without use any proxy configuration you need to set up the parameters as nil.
 +<sxh ruby>
 +require "​rubygems"​
 +require "​net/​http"​
 +require "​open-uri"​
 +
 +module Crawler
 + class NetHttp
 +   def initialize(proxy_host,​ proxy_port=80,​ proxy_user = nil, proxy_pass = nil)
 +     ​@proxy_host =  proxy_host;
 +     ​@proxy_port =  proxy_port;
 +     ​@proxy_user =  proxy_user;
 +     ​@proxy_pass =  proxy_pass;
 +   end
 +  ​
 +   def request_response(uri_str,​ limit = 10)
 +     begin
 +       http = Net::​HTTP::​Proxy(@proxy_host,​ @proxy_port,​ @proxy_user,​ @proxy_pass) ​     ​
 +       ​result = http.get_response(URI.parse(uri_str)) ​            
 +       case result
 +       when Net::​HTTPSuccess ​    then result
 +       when Net::​HTTPRedirection then request_response(result['​location'​],​ limit - 1)
 +       else
 +         ​result.error!
 +       end
 +     ​rescue Exception => e
 +         puts e.message
 +         ​return false
 +     end
 +   end
 + end
 +end
 +
 +c = Crawler::​NetHttp.new("<​http proxy URL>",​ "<​port >", "Proxy user name", "Proxy Password"​)
 +puts c.request_response("​http://​www.google.com/​search?​q=laptop"​);​
 +
 +</​sxh>​
 +
 +===== References =====
 +  - http://​chauhansudhir.blogspot.com.br/​2010/​12/​ruby-net-http-request-with-proxy.html