user2574121
user2574121

Reputation: 121

Build USPS web service request

I want to build a web service request which accesses USPS's address web service. I am facing a problem with building the request URL string in the format they want. What i want to do is give the zip code in a variable so that it can be dynamic. But USPS web service isn't accepting the URL string I am sending, guess I am making a mistake with the format.

The format which USPS expects is:

<CityStateLookupRequest USERID=”xxxxxxxx”>
<ZipCode ID="0">
<Zip5>90210</Zip5>
</ZipCode>
<ZipCode ID="1">
<Zip5>20770</Zip5>
</ZipCode>
</CityStateLookupRequest> 

https://servername/ShippingAPI.dll?API=CityStateLookup&XML=<CityStateLookupRe
quest USERID="username">.......</CityStateLookupRequest> 

This is how I am trying to build the URL:

WebRequest USPSReq = String.Format("http://production.shippingapis.com/ShippingAPI.dll?API=CityStateLookup&XML=CityStateLookupRequest&USERID=xxxxxxxx&ZipCode ID=0&Zip5=" + oZip);

How can I build this request URL?

Upvotes: 0

Views: 1702

Answers (1)

John Saunders
John Saunders

Reputation: 161773

Simply build that XML using your favorite XML API. For instance:

XDocument requestXml = new XDocument(
    new XElement("CityStateLookupRequest",
        new XAttribute("USERID", userID),
        new XElement("ZipCode",
            new XAttribute("ID", "0"),
            new XElement("ZIP5", zip5)));
var requestUrl = new UriBuilder("http://production.shippingapis.com/ShippingAPITest.dll");
requestUrl.Query = "API=CityStateLookup&XML=" + requestXml.ToString();
var request = WebRequest.Create(requestUrl.Uri);

Upvotes: 1

Related Questions