Home » Internet, Programming, Ruby

Making a HTTP GET request with ruby

24 July 2010 2 Comments

I had to get into some ruby programming for my job and so I decided to refresh my memories a bit more. It became more or less a tradition of mine to write some network or internet code to get into a language and so here’s a first result.

It’s just a simple function for making a HTTP request on a given target. On success it returns an HTTP object, on error nil. It’s nothing fancy, but it should be reliable and maybe helps someone for his/her project…

require 'net/http'
require 'uri'
require 'json'
 
# Simple HTTP GET request function
def makeRequest(target='')
  if target == '' || target == nil
    return nil
  else
    begin
      url = URI.parse(target)
      req = Net::HTTP::Get.new(target)
    rescue
      return nil
    end
  end
 
  begin
    res = Net::HTTP.start(url.host, url.port){ |http| http.request(req) }
  rescue
    res = nil
  end
  return res
end

A possible usage of the code could be:

target = 'http://search.twitter.com/trends/current.json'
out = makeRequest(target) || 'Error!';
json = JSON.parse(out.body) {|val| puts val}
puts json

This code fetches the current trending topics from twitter in JSON format.

Similar Posts:

2 Comments »

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.

Wo kommen bloß die ganzen Banner her?