Log in

Registration

HTTP Requests with Ruby

Posted: May 9, 2011 / in: Nuts and Bolts / No comments

ruby-logo-160Ruby is an full-featured cross-plattform programming language. It contains a number of modules that are expected to be contained in modern development environments.

This article illustrates how to utilize Ruby to access network resources via HTTP.

Overview

This article provides some basic example how to utilize the HTTP protocol to request data with GET requests.

Get Remote Data

The following script is a very basic one without any error handling implemented.

# load the HTTP related module
require 'net/http'
 
# request data via HTTP by utilizing an GET request
url = URI.parse('http://localhost/index.html')
req = Net::HTTP::Get.new(url.path)
res = Net::HTTP.start(url.host, url.port) {|http|
   http.request(req)
}
 
# print received data
puts res.body
 

 

The next example contains a block to perform error handling. The basic structure of the previous script did not change. (If you already know exception handling from other programming languages like Java, C# or Python you should not have any problems to understand the follwing script.)

# load the HTTP related module
require 'net/http'
 
begin
  url = URI.parse('http://localhost:3000/')
  req = Net::HTTP::Get.new(url.path)
  res = Net::HTTP.start(url.host, url.port) {|http|
     http.request(req)
  }
 
  puts res.body
rescue
  # print the error message
  puts $!
end
 
 

 

Post Data

To get an idea how things work in Ruby here is a very basic example how to send data via a POST request.

# load modules
require 'net/http'
 
# send the POST request
url = URI.parse('http://localhost/monitor/addService')
res = Net::HTTP.post_form(url, {'service' => 'Linux Support', 'max-alerts' => '50'})
 

 

To get an complete overview of available features please take a look into the following list of resources.

 

Additional resources:

© Copyrights and Licenses, 2012 - Linux-Support.com The Professional Linux and OSS Services Portal