65.9K
CodeProject is changing. Read more.
Home

UPS Address Validation Sample With ASP.NET and C#

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.06/5 (9 votes)

Oct 26, 2007

CPOL
viewsIcon

122849

downloadIcon

3811

A UPS Online Tool address validation sample with ASP.NET and C#.

Screen Shot

Introduction

I'm right now working on UPS online tool integration with my e-commerce web site. It is quite difficult to find sample source code for use with .NET. I created this article for .NET users who want to integrate their e-commerce web sites with the UPS Online Tool.

See details at UPS Online Tool.

Using the code

To use UPS address validation, you have to register a UPS account at UPS Account Register and request for a UPS access key at Get UPS Access Key.

To run my sample website, you have to replace your UPS account for user ID, password, and access key in the web.config.

<!-- Web.Config -->
<add key="AccessLicenseNumber" value="xxxxxxxxxxxxxxxx"/>
<add key="UserId" value="xxxxxx"/>
<add key="Password" value="xxxxxx"/>

This is the main code for the request address validation with the UPS online tool service.

// Create Request to UPS online tool address validation service
ASCIIEncoding encodedData = new ASCIIEncoding();
byte[] byteArray = encodedData.GetBytes(requestText);

// open up da site
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.Method = "POST";
wr.KeepAlive = false;
wr.UserAgent = "Benz";
wr.ContentType = "application/x-www-form-urlencoded";
wr.ContentLength = byteArray.Length;
try
{
    // send xml data
    Stream SendStream = wr.GetRequestStream();
    SendStream.Write(byteArray, 0, byteArray.Length);
    SendStream.Close();
    // get da response
    HttpWebResponse WebResp = (HttpWebResponse)wr.GetResponse();

    using (StreamReader sr = new StreamReader(WebResp.GetResponseStream()))
    {
        result = sr.ReadToEnd();
        sr.Close();
    } 

    WebResp.Close();
}
catch (Exception ex)
{
    // Unhandle exception occure
    result = ex.Message;
}