Class SimpleHttp
In: lib/simplehttp.rb
Parent: Object

Wrapper around ruby‘s standard net/http classes. Currently, only GET and POST https methods are supported. `SimpleHttp` provides class methods `get` and `post` to handle basic functionality. In case more complicated requests need to be made or default settings need to be overriden, it‘s possible to instantiate `SimpleHttp` and use instance methods `get` and `put`.

Features:

  • Handles Redirects automatically
  • Proxy used transparently if http_proxy environment variable is set.
  • SSL handled automatically
  • fault tolerant uri, e.g. all of these would work:
        "www.example.com", "www.example.com/", "http://www.example.com"
    

Some usage examples:

              # plain GET (using class methods)
              SimpleHttp.get "www.example.com"

              # POST using the instance methods
              uri = URI.parse "https://www.example.com/index.html"
              sh = SimpleHttp uri
              sh.set_proxy "my.proxy", "8080"
              sh.post {"query" => "query_data"}

              # POST using class methods.
              binaryData = getImage
              SimpleData.post binaryData, "image/png"

              # GET requst with a custom request_header
              sh = SimpleHttp.new "http://www.example.com"
              sh.request_headers= {'X-Special-Http-Header'=>'my-value'}
              sh.get

Methods

Constants

VERSION = '0.1.3'
RESPONSE_HANDLERS = { Net::HTTPResponse => lambda { |request, response, http| response.each_header {|key, value| http.response_headers[key]=value

Attributes

follow_num_redirects  [RW] 
proxy_host  [RW] 
proxy_port  [RW] 
proxy_pwd  [RW] 
proxy_user  [RW] 
request_headers  [RW] 
response_handlers  [RW] 
response_headers  [RW] 
uri  [RW] 

Public Class methods

Make a simple GET request to the provided URI.

Example:

     puts(SimpleHttp.get("www.example.com"))

[Source]

     # File lib/simplehttp.rb, line 338
338:         def self.get uri, query=nil
339:                 http = SimpleHttp.new uri
340:                 http.get query        
341:         end

[Source]

     # File lib/simplehttp.rb, line 343
343:         def self.head uri, query=nil
344:                 http = SimpleHttp.new uri
345:                 http.head query
346:         end

SimpleHttp can either be used directly through the get and post class methods or be instantiated, in case you need to to add custom behaviour to the requests.

@param may be a URI or a String.

Example:

     http = SimpleHttp.new(URI.parse("http://www.example.com"))
     http = SimpleHttp.new "www.example.com"
     http = SimpleHttp.new "http://usr:pwd@www.example.com:1234"

[Source]

     # File lib/simplehttp.rb, line 140
140:         def initialize uri
141:                 set_proxy ENV['http_proxy'] if ENV['http_proxy']
142:                                                 
143:                 if uri.class == String
144: 
145:                         unless uri =~ /^https?:\/\//
146:                                 uri = "http://#{uri}"
147:                         end
148: 
149:                         uri = URI.parse uri
150: 
151:                 end
152:                 @uri = uri
153:                 if !@uri.path || "" == @uri.path.strip
154:                         @uri.path="/"
155:                 end
156: 
157: 
158:                 @request_headers={}
159:                 @response_headers={}
160:                 @cookies=[]
161:                 @response_handlers=RESPONSE_HANDLERS.clone
162:                 @follow_num_redirects=5
163: 
164:                 if @uri.user
165:                         basic_authentication @uri.user, @uri.password
166:                 end
167: 
168:         end

[Source]

     # File lib/simplehttp.rb, line 348
348:         def self.options uri
349:                 http = SimpleHttp.new uri
350:                 http.options 
351:         end

Make a POST request to the provided URI.

Example:

     puts(SimpleHttp.post("www.example.com", "query"=>"my_query"))

Alternatively, you can post any sort of data, but will have to set the appriate content_type:

     SimpleHttp.post("http://www.example.com/", binary_data, "img/png")

[Source]

     # File lib/simplehttp.rb, line 368
368:         def self.post uri, query=nil, content_type='application/x-www-form-urlencoded'
369:                 http = SimpleHttp.new uri
370:                 http.post query, content_type
371:         end

[Source]

     # File lib/simplehttp.rb, line 353
353:         def self.trace uri
354:                 http = SimpleHttp.new uri
355:                 http.trace
356:         end

Public Instance methods

Provides facilities to perform http basic authentication. You don‘t need to provide usr and pwd if they are already included in the uri, i.e. user:password@www.example.com/

[Source]

     # File lib/simplehttp.rb, line 176
176:         def basic_authentication usr, pwd
177:                 str = Base64.encode64("#{usr}:#{pwd}")
178:                 str = "Basic #{str}"
179:                 @request_headers["Authorization"]=str
180:         end

internal

[Source]

     # File lib/simplehttp.rb, line 310
310:         def do_http request
311:                 response = nil
312: 
313:                 http = Net::HTTP.new(@uri.host, @uri.port, @proxy_host,
314:                         @proxy_port, @proxy_user, @proxy_pwd)
315:                 http.use_ssl = @uri.scheme == 'https'
316:         
317:                 # add custom request headers.
318:                 
319:                 @request_headers.each {|key,value|
320:                         request[key]=value;
321:                 }
322: 
323:                 handle_response(request, http.request(request));
324:         end

Call the get method as an instance method if you need to modify the default behaviour of the library, or set special headers:

     http = SimpleHttp.new "www.example.com"
     http.request_headers["X-Special"]="whatever"
     str = http.get

[Source]

     # File lib/simplehttp.rb, line 380
380:         def get query = nil
381:                 if (query = make_query query)
382:                         @uri.query = @uri.query ? @uri.query+"&"+query : query
383:                 end
384:                 full_path = @uri.path + (@uri.query ? "?#{@uri.query}" : "")
385:                         
386:                 req = Net::HTTP::Get.new(full_path)
387:                 # puts Net::HTTP::Proxy(@proxy_host, @proxy_port, @proxy_user, @proxy_pwd).get(@uri)
388:                 do_http req
389:         end

interal Takes a HTTPResponse (or subclass) and determines how to handle the response. Default behaviour is:

     HTTPSuccess : return the body of the response
     HTTPRedirection : follow the redirect until success.
     default : raise the HTTPResponse.

the default behaviour can be overidden by registering a response handler using the `register_response_handler` method.

[Source]

     # File lib/simplehttp.rb, line 287
287:         def handle_response http_request, http_response
288:                 raise "Not a Net::HTTPResponse" unless http_response.is_a? Net::HTTPResponse
289:                 
290:                 c = http_response.class
291:                 while c!=Object
292:                         # the response_handlers hash contains a handler
293:                         # for the specific response class.
294:                         if @response_handlers[c]
295:                         #STDERR.puts "!#{http_response.class}"
296:                         #STDERR.puts "!#{@response_handlers[c]}"
297:                                 return @response_handlers[c].call(http_request, http_response, self)
298:                         end
299: 
300:                         c=c.superclass
301:                 end   
302: 
303:                 # if we reached this place, no handler was registered
304:                 # for this response. default is to return the response.
305:                 
306:                 return http_response
307:         end

Call the head method as an instance method.

[Source]

     # File lib/simplehttp.rb, line 393
393:         def head query = nil
394:                 if (query = make_query query)
395:                         @uri.query = @uri.query ? @uri.query+"&"+query : query
396:                 end
397:                 full_path = @uri.path + (@uri.query ? "?#{@uri.query}" : "")
398:                         
399:                 req = Net::HTTP::Head.new(full_path)
400:                 # puts Net::HTTP::Proxy(@proxy_host, @proxy_port, @proxy_user, @proxy_pwd).get(@uri)
401:                 do_http req
402:         end

internal

[Source]

     # File lib/simplehttp.rb, line 327
327:         def make_query query
328:                 return query unless query && query.class == Hash
329:                 query.inject([]) do |s, (key, value)|
330:                         s << CGI::escape(key) + "=" + CGI::escape(value)
331:                 end.join('&')
332:         end

Call http options method. Returns the response

[Source]

     # File lib/simplehttp.rb, line 405
405:         def options
406:                 # we don't support sending a payload in options' body.
407:                 req = Net::HTTP::Options.new(@uri.path)
408:                 do_http req
409:         end

Post the query data to the url. The body of the request remains empty if query=nil. In case `query` is a `Hash`, it‘s assumed that we are sending a form. In case `query` is a `String`, it‘s also assumed that a form is being sent, UNLESS the `content_type` parameter is set.

[Source]

     # File lib/simplehttp.rb, line 426
426:         def post query=nil, content_type='application/x-www-form-urlencoded'
427:                 req = Net::HTTP::Post.new(@uri.path)
428: 
429:                 req.body= make_query query if query
430:                 req.content_type=content_type if query
431:                 req.content_length=query ? req.body.length : 0
432: 
433:                 do_http req
434:         end

this method can be used to register response handlers for specific http responses in case you need to override the default behaviour. Defaults are:

     HTTPSuccess : return the body of the response
     HTTPRedirection : follow the redirection until success
     Others : raise an exception

`clazz` is the subclass of HTTPResponse (or HTTPResponse in case you want to define "default" behaviour) that you are registering the handler for.

`block` is the handler itself, if a response of the appropriate class is received, `block` is called with three parameters: the the Net::HTTPRequest, the actual HTTPResponse object that was received and a reference to the instance of `SimpleHttp` that is executing the call.

example:

     # to override the default action of following a HTTP
     # redirect, you could register the folllowing handler:

     sh = SimpleHttp "www.example.com"
     sh.register_response_handler Net::HTTPRedirection {|request, response, shttp|
             response['location']
     }

[Source]

     # File lib/simplehttp.rb, line 212
212:         def register_response_handler clazz, &block
213:                 c = clazz
214:                        while c != Object
215:                         # completely unnecessary sanity check to make sure parameter
216:                         # `clazz` is in fact a HTTPResponse ...
217:                         if c == Net::HTTPResponse
218:                                 @response_handlers[clazz]=block 
219:                                 return
220:                         end
221:                         c = c.superclass
222:                 end
223: 
224:                 raise "Trying to register a response handler for non-response class: #{clazz}"        
225:         end

Set the proxy to use for the http request. Note that you don‘t need to set the proxy in case the `http_proxy` environment variable is set. To override previous proxy settings and connect directly, call `set_proxy nil`

usage:

        http = SimpleHttp.new "www.example.com"

        http.set_proxy "http://proxy:8000"

or:

        http.set_proxy(URI.parse("http://proxy:8000"))

or:

        http.set_proxy 'proxy', '8000', 'my_user', 'secret'

or:

        http.set_proxy nil # to override previous proxy
        settings and make the request directly.

[Source]

     # File lib/simplehttp.rb, line 248
248:         def set_proxy proxy, port=nil, user=nil, pwd=nil
249:                 
250:                 
251:                 if !proxy     
252:                         @proxy_host=@proxy_port=@proxy_user=@proxy_pwd=nil 
253:                         return
254:                 end
255: 
256:                 if proxy.class == String 
257:                         if !port && !user && !pwd
258:                                 proxy = URI.parse(proxy)
259:                         else 
260:                                 @proxy_host= host
261:                                 @proxy_port= port
262:                                 @proxy_user= user
263:                                 @proxy_pwd = pwd
264:                         end
265:                 end
266:                 
267:                 if proxy.class == URI::HTTP 
268:                         @proxy_host= proxy.host
269:                         @proxy_port= proxy.port
270:                         @proxy_user= proxy.user
271:                         @proxy_pwd = proxy.password
272:                 end
273:         end

[Source]

     # File lib/simplehttp.rb, line 411
411:         def trace
412:                 # payload? 
413:                 req = Net::HTTP::Trace.new(@uri.path)
414:                 do_http req
415:         end

[Validate]