【发布时间】:2011-02-19 09:23:41
【问题描述】:
我想向 USPS 验证给定地址(地址、城市、州、邮编),如果提供的地址是有效地址,则返回结果。如果不是有效地址,则返回无效地址。
那么我如何在 C#.Net 中做到这一点。
【问题讨论】:
标签: c#
我想向 USPS 验证给定地址(地址、城市、州、邮编),如果提供的地址是有效地址,则返回结果。如果不是有效地址,则返回无效地址。
那么我如何在 C#.Net 中做到这一点。
【问题讨论】:
标签: c#
美国邮政服务 (USPS) 确实通过其地址信息 API 提供此服务:
这是一篇关于如何在 .NET 中使用此服务的代码项目文章/库:
注意
【讨论】:
来自here
///Create a new instance of the USPS Manager class
///The constructor takes 2 arguments, the first is
///your USPS Web Tools User ID and the second is
///true if you want to use the USPS Test Servers.
USPSManager m = new USPSManager("YOUR_USER_ID", true);
Address a = new Address();
a.Address2 = "6406 Ivy Lane";
a.City = "Greenbelt";
a.State = "MD";
///By calling ValidateAddress on the USPSManager object,
///you get an Address object that has been validated by the
///USPS servers
Address validatedAddress = m.ValidateAddress(a);
注意:出于某种原因,您需要将实际地址作为地址 2。如果您尝试将 Address1 设置为“6406 Ivy Lane”,它将失败。 Address1 显然是公寓或套房号。 感谢Simon Weaver下方的评论。
【讨论】:
如果我可以在这里插话——我曾经在 SmartyStreets 的地址验证行业工作,SmartyStreets 是这些服务的 CASS 认证供应商。
首先请注意,虽然 USPS 是地址数据的权威机构,但他们的强项不是维护 API 和提供支持。另外,请务必注意您签署的协议:
- 用户同意仅使用 USPS 网站、API 和 USPS 数据来促进 USPS 运输交易。
因此,除非您使用 USPS 的 API 邮寄或运送,否则使用 API 是不可接受的。在您遇到的其他问题中,有理由寻找更好的解决方案——如果我是您的话。
无论如何,实际上有不少。我会让你自己做研究,但我当然会建议我研究过的一个叫做 LiveAddress。它是免费的,并且比 USPS 的 API 返回更多数据并且更可靠。
更新: Here's some C# code examples on GitHub 这可能会有用。
【讨论】:
服务对象地址验证 Web 服务可以根据 USPS 确定地址是否有效。下面是几个 C# 示例(RESTful 请求和 SOAP 请求):
宁静的请求
string mainURL = "https://trial.serviceobjects.com/AV3/api.svc/GetBestMatchesJson/" + businessName + "/" + address + "/" + address2 + "/" + city + "/" + state + "/" + zip + "/" + licenseKey;
AV3Response result = null;
HttpWebRequest request = WebRequest.Create(mainURL ) as HttpWebRequest;
request.Timeout = 5000;//timeout for get operation
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
response.StatusCode,
response.StatusDescription));
//parse response
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(AV3Response));
object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
result = objResponse as AV3Response;
//processing result
if (result.error == null)
{
//process result
}
else
{
//process error
}
另一种选择是使用 wsdl 并发出 SOAP 请求。
SOAP 请求
//Add a service to your application https://trial.serviceobjects.com/av3/api.svc/
AV3Client_Primary = new AddressValidation3Client("DOTSAddressValidation3");
response = AV3Client_Primary.GetBestMatches(Business, Address, Address2, City, State, PostalCode, licenseKey);
响应字段将包含有关地址有效性的信息。 DPV 分数可用于确定地址是否可送达、不可送达或接近正确但缺少一些重要信息(apt、ste、rr #)。
如果您想了解有关服务输出的更深入信息,可以查看here
【讨论】: