Code Snippet: Making a HTTP GET request with ruby

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:

  • Uri

    Most request_rec structures are built by reading an HTTP request from a client, and filling in the fields. Uri