USPS 地址验证 API :如果地址字段中有 & 或 # 符号,则 API returns 错误响应

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

我已经编写了一个 C# 代码来访问 USPS 地址验证 API。 如果 没有 & 或 # 符号,API 会返回正确的响应。 但是如果请求有 # 或 & 符号,那么我会收到错误响应。

我正在使用 System.Xml.Linq 库构建一个 XML 字符串。

差异输出。 1) 如果地址包含#

<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) **如果地址中包含 & 则转换为 & amp;通过 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>

这是我写的C#代码。

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;
    }
}

这是一个示例请求。

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>

如有任何帮助,我们将不胜感激。

我在 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.

所以看起来您要么需要转义,要么需要对它们进行 url 编码。 & 解码为 %26,# 解码为 %23

这在一个应用程序中对我有用:将 & 编码为 %26amp;%26 编码 &amp; 编码的前导符号。