1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

FREE C# - POSTCODE CHECKER courtesy of Yahoo

Discussion in 'C, C++, C#' started by divinci, Jan 13, 2010.

  1. divinci

    divinci Junior Member

    Joined:
    Sep 25, 2007
    Messages:
    111
    Likes Received:
    15
    Enjoy!

    Will be posting tidbits as and when.

    Code:
    using System;
    using System.Net.Sockets;
    using System.Net.Security;
    using System.Net;
    using System.Text;
    
    namespace divinci.Net.Web.Utils
    {
    
        public enum PostCodeType
        {
            US,
            UK
        }
    
        public static class YahooUSApi
        {
            public static bool IsValidZipCode(string postCode, PostCodeType postCodeType)
            {
                string host = "edit.yahoo.com";
    
                string httpRequest =string.Format(@"GET /reg_json?PartnerName=yahoo_default&RequestVersion=1&PostalCode={0}&Country={1}&ApiName=ValidateFields HTTP/1.1
    Accept: */*
    Accept-Language: en-us
    x-requested-with: XMLHttpRequest
    User-Agent: divinci.Net.Web
    Host: {2}
    Connection: Keep-Alive
    
    ", Uri.EscapeDataString(postCode), postCodeType.ToString().ToLower(),host);
    
                byte[] httpRequestBytes = Encoding.UTF8.GetBytes(httpRequest);
                byte[] httpResponseBytes = new byte[1000]; // 1K read buffer. will do
    
                using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    socket.Connect(host, 443);
                    using (NetworkStream networkStream = new NetworkStream(socket))
                    {
                        using (SslStream sslStream = new SslStream(networkStream))
                        {
                            // start an SSL transaction
                            sslStream.AuthenticateAsClient(host);
    
                            // send the HTTP request
                            sslStream.Write(httpRequestBytes, 0, httpRequestBytes.Length);
    
                            // read the responce
                            int bytesRead = sslStream.Read(httpResponseBytes, 0, httpResponseBytes.Length);
    
                            string httpResponseBytesString = Encoding.UTF8.GetString(httpResponseBytes);
                            if (httpResponseBytesString.Contains("SUCCESS"))
                                return true;
                            else
                                return false;
                        }
                    }
                }
            }
        }
    }