There are a couple of more important steps to getting this request properly formatted. You need to
escape the special characters of the request with the two lines of code in Listing 9.
Listing 9. Escape the request’s special characters
uri_enc = URI.escape(‘http://testing.shippingapis.com/ShippingAPITest.dll
?API=CityStateLookup&XML=’ + xmlstuff)
uri = URI.parse(uri_enc)
These lines take care of the conversion of all the special characters into proper encoding as an HTTP
request. I’ll leave it up to you to improve this code by setting up variables or property files for the
server name, API name, and so on. Your goal is just to get the call to the Web service working; you
can polish and refine later. Now you have a properly formatted HTTP/XML request and are ready to
invoke the USPS Web service.
Step 6: Call the Web service and receive a response
In this step, you call the USPS Web service and receive a response. The code must parse the XML
response. Listing 10 shows a sample of a USPS CityStateLookup response.
Listing 10. USPS CityStateLookup response
<?xml version=”1.0"?>
<CityStateLookupResponse><ZipCode ID=”0"><Zip5>90210</Zip5>
<City>BEVERLY HILLS</City><State>CA</State></ZipCode>
</CityStateLookupResponse>
Again, I took this example directly from the USPS Web Tools documentation. Your goal in this step
is to parse the city and state information and place it in your @address object’s variables. Eventually
those variables are returned as a part of the Ajax response.
Keep this in mind: the Builder library allows for creation of the XML, while the module REXML
enables parsing the XML data.
Listing 11. Call the Web Service and parse the response (addressadmin_controller.rb)
# The call to the Web service — response is in var ‘doc’
doc = REXML::Document.new open(uri)
logger.debug(“doc = “ + doc.to_s)
doc.elements.each(“CityStateLookupResponse/ZipCode”) { |element|
logger.debug(element)
logger.debug(“element[0] = “ + element[0].to_s)
logger.debug(“element[0].text = “ + element[0].text)
logger.debug(“element[1] = “ + element[1].to_s)
logger.debug(“element[1].text = “ + element[1].text)
logger.debug(“element[2] = “ + element[2].to_s)
logger.debug(“element[2].text = “ + element[2].text)
# Set the model field values to the response from the Web service
@address.city = element[1].text
@address.state = element[2].text
} |