Search code examples
c#xmlapiusps

USPS address validation API : If & or # symbol in address field then API returns error response


I have written a C# code to access the USPS Address validation API. The API is returning a proper response if there is no & or # symbol. But if the request has # or & symbol then I am getting an error response.

I am using System.Xml.Linq library to build an XML string.

Diff outputs. 1) If the address contains #

<Error>
  <Number>80040B19</Number>
  <Description>XML Syntax Error: Please check the XML request to see if it can be parsed.(B)</Description>
  <Source>USPSCOM::DoAuth</Source>
</Error>

2) **if the address contains & which is converted to & amp; by XDocument **

<Error>
  <Number>80040B18</Number>
  <Description>An error has occurred with the service.  Please contact the system administrator, or try again.</Description>
  <Source>USPSCom::DoAuth</Source>
</Error>

Here is the C# code which I have written.

public static XDocument ValidateUSPSAddress(string address1, string address2, string city, string state, string zip)
    {
        XDocument xmlResponse;
        XDocument requestDoc = new XDocument(
            new XElement("AddressValidateRequest",
                    new XAttribute("USERID", UserID),
                new XElement("Revision", "1"),
                new XElement("Address",
                        new XAttribute("ID", 0),
                    new XElement("Address1", address1),
                    new XElement("Address2", address2),
                    new XElement("City", city),
                    new XElement("State", state),
                    new XElement("Zip5", zip),
                    new XElement("Zip4", "")
                )
           )
       );
        try
        {
            var url = Endpoint + VerifyParam + String.Format(XMLParam, requestDoc);
            var clinet = new WebClient();
            var response = clinet.DownloadData(url);
            xmlResponse = XDocument.Parse(System.Text.Encoding.UTF8.GetString(response));
        }
        catch (WebException ex)
        {
            throw ex;
        }

        return xmlResponse;
    }
}

and here is a sample request.

http://production.shippingapis.com/ShippingAPI.dll?API=Verify&XML=<AddressValidateRequest USERID="###########">
  <Revision>1</Revision>
  <Address ID="0">
    <Address1></Address1>
    <Address2>29851 Aventura &amp; avenue</Address2>
    <City></City>
    <State>CA</State>
    <Zip5>92688</Zip5>
    <Zip4></Zip4>
  </Address>
</AddressValidateRequest>

Any help would be appreciated.


Solution

  • I found a small reference to this in the Development Guide

    ISO-8859-1 encoding is the expected character set for the request. Make sure that special characters embedded in any tag data such as & < > are escaped and url-encoded.

    So it looks like you either need to escape and url encode them. & decodes to %26 and # decodes to %23