
This HOWTO describes how to perform GET and POST requests using Net::HTTP and Net::HTTPS, both part of the Ruby standard library.
The simplest way of retrieving data from a URL is to use the get_response method:
require 'net/http' url = 'http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=madonna&results=1' resp = Net::HTTP.get_response(URI.parse(url)) # get_response takes an URI object data = resp.body
The URL should not contain illegeal characters. Hence the query parameter which, in many cases, will be accepted as user input, needs to be encoded using the URI.encode method.
url = "http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=#{URI.encode("premshree pillai")}&results=1"
The above code would work fine, but you need a way to handle excpetions—in case of 404 or 500 errors:
require 'net/http' begin data = Net::HTTP.get_response(URI.parse(url)).body rescue print "Connection error." end
Some APIs require you to make POST requests. Net::HTTP provides a post method for this:
require 'net/http'
url = URI.parse('http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction')
appid = 'YahooDemo'
context = 'Italian sculptors and painters of the renaissance favored
the Virgin Mary for inspiration'
query = 'madonna'
post_args = {
'appid' => appid,
'context' => context,
'query' => query
}
resp, data = Net::HTTP.post_form(url, post_args)
The del.icio.us API requires you to make authenticated requests, passing your del.icio.us username and password using HTTP authentication. Net::HTTP provides a mechanism for doing this.
require 'net/https'
http = Net::HTTP.new('api.del.icio.us', 443)
http.use_ssl = true
http.start do |http|
req = Net::HTTP::Get.new('/v1/tags/get')
# we make an HTTP basic auth by passing the
# username and password
req.basic_auth 'username', 'password'
resp, data = http.request(req)
end
Copyright © 2008 Yahoo! Inc. All rights reserved.
Privacy Policy - Terms of Service - Copyright Policy - Job Openings