simple, this code only passes one ZIP code, which has the XML tag <ZipCode ID= “0”>. So the
functionality becomes quite obvious: You need to get the five-digit value entered by the user and
put it into this XML tag named <Zip5>.
So what kind of Web service is this?
It turns out that this seemingly simple question isn’t always easy to answer. Web services have
become like Baskin Robbins’ 31 flavors of ice cream or the Starbucks coffee menu. It seems like
ordering a cup of coffee should be easy to do until they hit you with something called a Grande Chai
Latte with Soy. First, what it’s not: This isn’t a XML-RPC-style Web service, document-style Web
service, SOAP Web service, or Representational State Transfer (REST) (noun-based) request Web
service. The designers at the USPS have decided to implement this as a plain vanilla XML Web
service. The USPS Web servers accept either GET or POST HTTP requests. The requests are
stateless with no cookies or URL rewrites. Requests and responses are case sensitive. Once again,
it’s easy to register with USPS Web Tools, and there’s plenty of documentation. (I should note that
I have no affiliation with the USPS.)
To create the XML, you use the Builder::XmlMarkup library, which is included with RoR. At the
beginning of the controller class file addressadmin_controller.rb, you need to add the code shown in
Listing 7.
Listing 7. Code to be added to addressadmin_controller.rb
require ‘open-uri’
require ‘uri’
require ‘rubygems’
require_gem ‘builder’
require “rexml/document”
Listing 8. Create the XML portion of the request
01 def cityStateSearch
02
03 if params[:zip5].nil?
04 logger.debug(“zip5 is null”)
05 elsif !(params[:zip5] =~ /\d{5}/)
06 logger.debug(“We have a bad ZIP code — not 5 digits.”)
07 logger.debug(“zip5 = #{params[:zip5]}”)
08 else
09 logger.debug(“We have a good 5-digit ZIP code.”)
10 logger.debug(“zip5 = #{params[:zip5]}”)
11 # Build the XML to call the web service
12 xm = Builder::XmlMarkup.new
13 xmlstuff = xm.CityStateLookupRequest(“USERID”=>”XXXXXXXXXXXX”) {
14 xm.ZipCode(“ID”=>”0") {
15 xm.Zip5(params[:zip5]) }}
16
17 end
18 end #cityStateSearch
Just four lines, lines 12 through 15, create the properly formatted XML for the request. The string
variable xmlstuff contains this XML:
<CityStateLookupRequest%20USERID=”XXXXXXXXXXXX”><ZipCode ID= “0”><Zip5>90210</Zip5></ZipCode></CityStateLookupRequest> |