How to validate the given address using USPS?

前端 未结 4 1054
囚心锁ツ
囚心锁ツ 2021-02-01 23:29

I want to validate the given address (address, city, state, zip) to the USPS and return back the result if the provided address is a valid address. and if it is not the valid ad

4条回答
  •  孤街浪徒
    2021-02-02 00:12

    The Service Objects address validation web service can determine if an address is valid according to the USPS. Below are a couple of C# examples (RESTful request and SOAP request):

    Restful request

    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
    }
    

    The other option is to consume the wsdl and make a SOAP request.

    SOAP request

    //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);
    

    The response field will contain information about the validity of the address. The DPV score can be used to determine if an address is deliverable, non deliverable, or is close to correct but missing some vital piece of information (apt, ste, rr #).

    DPV Codes

    If you'd like more in depth information on the service's outputs you can check out here

提交回复
热议问题