Advertisement
Guest User

C# - Busca de Endereço por CEP no Site dos Correios

a guest
Apr 4th, 2012
963
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.06 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using System.Net;
  10. using System.Net.Sockets;
  11. using System.Windows.Forms;
  12. using System.IO;
  13. using System.Threading;
  14. using System.Net.Security;
  15.  
  16. namespace EndereçoPeloCep
  17. {
  18.     public partial class Form1 : Form
  19.     {
  20.         public Form1()
  21.         {
  22.             InitializeComponent();
  23.         }
  24.  
  25.         private void button1_Click(object sender, EventArgs e)
  26.         {
  27.             /**
  28.              *
  29.              * Verifica se o cep digitado é válido.
  30.              *
  31.              */
  32.             Match regex = Regex.Match(textBox1.Text, "^[0-9]{8}$");
  33.  
  34.             /**
  35.              *
  36.              * Se o CEP digitado for valido...
  37.              *
  38.              */
  39.             if (regex.Success)
  40.             {
  41.                 listBox1.Items.Clear();
  42.  
  43.                 try
  44.                 {
  45.                     /**
  46.                      *
  47.                      * CEP a ser pesquisado
  48.                      *
  49.                      */
  50.                     string cep = textBox1.Text;
  51.  
  52.                     /**
  53.                      *
  54.                      * Cria a requisição
  55.                      *
  56.                      */
  57.                     HttpWebRequest Request =
  58.                         (HttpWebRequest)WebRequest.Create("http://www.buscacep.correios.com.br/servicos/dnec/consultaEnderecoAction.do");
  59.  
  60.                     /**
  61.                      *
  62.                      * Define o que será postado
  63.                      *
  64.                      */
  65.                     string postData = "relaxation=" + cep + "&TipoCep=ALL&semelhante=N&Metodo=listaLogradouro&TipoConsulta=relaxation&StartRow=1&EndRow=10&cfm=1";
  66.  
  67.                     /**
  68.                      *
  69.                      * Converte a string de post para um ByteStream
  70.                      *
  71.                      */
  72.                     byte[] postBytes = Encoding.ASCII.GetBytes(postData);
  73.  
  74.                     /**
  75.                      *
  76.                      * Parâmetros da requisição
  77.                      *
  78.                      */
  79.                     Request.Method = "POST";
  80.                     Request.ContentType = "application/x-www-form-urlencoded";
  81.                     Request.ContentLength = postBytes.Length;
  82.  
  83.                     Stream requestStream = Request.GetRequestStream();
  84.  
  85.                     /**
  86.                      *
  87.                      * Envia Requisição
  88.                      *
  89.                      */
  90.                     requestStream.Write(postBytes, 0, postBytes.Length);
  91.                     requestStream.Close();
  92.  
  93.                     /**
  94.                      *
  95.                      * Resposta do servidor dos correios
  96.                      *
  97.                      */
  98.                     HttpWebResponse response = (HttpWebResponse)Request.GetResponse();
  99.                     listBox1.Items.Add("Resposta do Servidor: " + response.StatusCode.ToString());
  100.  
  101.                     /**
  102.                      *
  103.                      * String com a resposta do servidor
  104.                      *
  105.                      */
  106.                     string responseText = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
  107.  
  108.                     /**
  109.                      *
  110.                      * Separa os dados com expressão regular
  111.                      *
  112.                      */
  113.                     MatchCollection matches = Regex.Matches(responseText, ">(.*?)</td>");
  114.  
  115.                     /**
  116.                      *
  117.                      * Exibe os dados recebidos
  118.                      *
  119.                      */
  120.                     UTF8Encoding utf8 = new UTF8Encoding();
  121.  
  122.                     /**
  123.                      *
  124.                      * @ RUA
  125.                      * Passa o texto convertido para a textBox
  126.                      *
  127.                      */
  128.                     textBox2.Text = matches[0].Groups[1].ToString();
  129.  
  130.                     /**
  131.                      *
  132.                      * @Bairro
  133.                      *
  134.                      */
  135.                     textBox3.Text = matches[1].Groups[1].ToString();
  136.  
  137.                     /**
  138.                      *
  139.                      * @Cidade
  140.                      *
  141.                      */
  142.                     textBox4.Text = matches[2].Groups[1].ToString();
  143.  
  144.                     /**
  145.                      *
  146.                      * @Estado
  147.                      *
  148.                      */
  149.                     textBox5.Text = matches[3].Groups[1].ToString();
  150.                 }
  151.                 catch (Exception ex)
  152.                 {
  153.                     listBox1.Items.Clear();
  154.                     listBox1.Items.Add("! Erro na execução: " + ex.ToString());
  155.                 }
  156.             }
  157.             else
  158.             {
  159.                 listBox1.Items.Clear();
  160.                 listBox1.Items.Add("CEP inválido");
  161.             }
  162.         }
  163.     }
  164. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement