How to find a postal address in the Post Office?

145

How do I search the post office for the details of an address using your zip code (similar to the address records we see on e-commerce sites)?

    
asked by talles 15.12.2013 в 04:33

19 answers

72

The post office offers this information through the e-DNE (National Address Book).

  

In 2000, the Post Office launched the National Directory of Addresses (DNE), a database containing the CEP of all Brazil and elements of address (description of streets, neighborhoods, municipalities, towns, villages).

p>      

In 2012, the Post Office innovated the DNE and launched the e-DNE, which was purchased in a few minutes via the Internet in the Post Office virtual store by download. Today your purchase no longer requires formalization of contract, it is only made through adherence to the Term of Commitment.

( font )

The e-DNE is a downloadable database in text (.txt) and MS-Access (.mdb) formats.

This database is paid, including your updates . You can purchase at Online Store (prices range from around $ 220 to $ 2,500).

Unfortunately this is the only form available by the Post Office access to your ZIP code base; a webservice would be more efficient ( for other services they provide ).

    
15.12.2013 / 04:33
90

You can use the Postmon API.

They use an online database of Post Office Postcodes for searches that are not yet locally cached in Postmon.

For example, you can get JSON address information from a zip code using the API:

http://api.postmon.com.br/v1/cep/*cep_a_consultar*

In addition the Postmon code is open and available at Github .

    
16.12.2013 в 18:24
48

I think it's even easier to have everyone listed, even more so that there are some repeated in different responses.

And if you know anything else to have in the list you will be welcome, just edit !

    
23.09.2014 в 21:23
24

In C # using webservice link as pointed out by our colleague @ talles looks like it has not been updated in quite a while, I was able to quickly do a few lines of code :

string cep = "01010-010"; // Contém o CEP que será pesquisado
// Objeto DataSet que receberá a tabela em XML que contém os dados da pesquisa
DataSet ds = new DataSet();
// Armazena o arquivo XML retirado da página onde o CEP foi pesquisado
ds.ReadXml("http://cep.republicavirtual.com.br/web_cep.php?cep=" + cep);
// Caso tenha encontrado o CEP o valor da primeira célula da primeira linha da tabela será 1 
if (ds.Tables[0].Rows[0][0].ToString() == "1")
{
    // Repassa os valores contidos nas células da primeira linha para suas
    // respectivas TextBox'es, para serem exibidos para o usuário
    textBoxUf.Text = ds.Tables[0].Rows[0]["uf"].ToString().Trim();
    textBoxCidade.Text = ds.Tables[0].Rows[0]["cidade"].ToString().Trim();
    textBoxBairro.Text = ds.Tables[0].Rows[0]["bairro"].ToString().Trim();
    textBoxTipoLogradouro.Text =
        ds.Tables[0].Rows[0]["tipo_logradouro"].ToString().Trim();
    textBoxEnd.Text = ds.Tables[0].Rows[0]["logradouro"].ToString().Trim();
    textBoxStatus.Text = "CEP completo";
}
else
{
    MessageBox.Show("CEP não encontrado.");
}
    
15.12.2013 в 16:25
22

Using the post office itself, using PHP, using DOM + XPath:

function buscaCEP($cep)
{
    $response = file_get_contents(
        'http://m.correios.com.br/movel/buscaCepConfirma.do',
        false,
        stream_context_create([
            'http' => [
                'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
                'method' => 'POST',
                'content' => http_build_query([
                    'cepEntrada' => $cep,
                    'metodo' => 'buscarCep',
                ]),
            ],
        ])
    );

    $dom = new DOMDocument();
    @$dom->loadHTML($response);
    $xpath = new DOMXPath($dom);
    $values = $xpath->query('//*[@class="respostadestaque"]');
    $result = [];

    // Se não encontrar CEP, retorna false
    if (!$values->length) {
        return false;
    }

    // Obtém informações desejadas, tratando-as quando necessário
    foreach ($values as $value) {
        $result[] = preg_replace(
            '~[\s]{2,}~',
            '',
            trim($value->childNodes->item(0)->nodeValue)
        );
    }

    if ($values->length > 2) {
        // CEPs de logradouros
        list($logradouro, $bairro, $localidade, $cep) = $result;
    } else {
        // CEPs de localidades
        list($logradouro, $bairro) = null;
        list($localidade, $cep) = $result;
    }

    list($localidade, $uf) = explode('/', $localidade);

    return compact('logradouro', 'bairro', 'localidade', 'uf', 'cep');
}
    
22.12.2013 в 02:49
15

boy, have the webservice of the virtual republic, take a look at it, if you look for address data by zip code, just use a javascript that they provide there, I've already used it on a mine site and it works which is a marvel. link

    
15.12.2013 в 15:09
13

In this example, I'm using javascript and browsing the webservice of the Virtual Republic.

I look for the address in this API using the zip code, and I fill in the fields type of public place , neighborhood , city and uf with the information received.

<script type="text/javascript">


$(document).ready(function(){
    $("#cep").blur(function(e){
        if($.trim($("#cep").val()) != ""){
            $.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cep").val(), function(){
                if(resultadoCEP["resultado"]){
                    $("#rua").val(unescape(resultadoCEP["tipo_logradouro"])+": "+unescape(resultadoCEP["logradouro"]));
                    $("#bairro").val(unescape(resultadoCEP["bairro"]));
                    $("#cidade").val(unescape(resultadoCEP["cidade"]));
                    $("#estado").val(unescape(resultadoCEP["uf"]));
                }else{
                    alert("Não foi possivel encontrar o endereço");
                }
            });             
        }
    })
});
</script>

    
17.12.2013 в 12:39
13

There is a very simple way

function getEndereco() {

    if ($.trim($("#cep").val()) !== "") {
        $.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep=" + $("#cep").val(), function() {

            if (resultadoCEP["resultado"]) {
                $("#rua").val(unescape(resultadoCEP["tipo_logradouro"]) + " " + unescape(resultadoCEP["logradouro"]));
                $("#bairro").val(unescape(resultadoCEP["bairro"]));
                $("#cidade").val(unescape(resultadoCEP["cidade"]));
                $("#estado").val(unescape(resultadoCEP["uf"]));
                $("#pais").val('Brasil');
                $("#numero").focus();
            }
        });
    }

}

It returns a Json and you just need to add the fields where needed.

    
16.12.2013 в 11:59
13

An alternative is the Open CEP : "[...] a project that aims to provide free access and collaboratively build a data with geolocated postal codes (ZIP codes) of all Brazil. ".

The database has 917952 zip codes, most of which are geolocated, i.e., have latitude and longitude. Geolocation is not always accurate, so it's worth helping the project.

To use the API you need to register for free and you will receive a unique token. And internally there is an interface with simple graphics showing your use of the API.

An example of how to use the Open Python zip API:

from urllib2 import urlopen, Request
url = "http://www.cepaberto.com/api/v1/ceps.json?cep=40010000"
headers = {'Authorization': 'Token token=SEU_TOKEN_PESSOAL_AQUI'}
json = urlopen(Request(url, None, headers=headers)).read()
print json
{"altitude":8, "bairro":"Comércio", "cep":"40010000", "cidade":"Salvador", "ddd":71, "ibge":"2927408", "latitude":"-12.971", "logradouro":"Avenida da Franca", "longitude":"-38.511"}
    
31.07.2014 в 18:03
11

Function using Java, with full return of data including IBGE code

public XmlCep buscaEnderecoCep(String nrCep,String format) {

    XmlCep xmlCep = null;   

    StringBuffer url= new StringBuffer();       
    url.append("http://viacep.com.br/ws/");     
    url.append(nrCep);
    url.append("/"+format);     

    HttpClient client = new DefaultHttpClient();            
    HttpGet method = new HttpGet(url.toString());            
    method.addHeader("User-Agent", USER_AGENT);

    try {   

        HttpResponse response = client.execute(method);
        System.out.println("\nSending 'GET' request to URL : " + url.toString());           
        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());  

        HttpEntity entity = response.getEntity();
        String resultado = EntityUtils.toString(entity,"UTF-8");            

        System.out.println(resultado);

         if(resultado!=null) {          
             XStream stream = new XStream(new DomDriver());
             stream.autodetectAnnotations(true);
             stream.aliasSystemAttribute(null, "class");
             stream.processAnnotations(XmlCep.class);   
             xmlCep = (XmlCep) stream.fromXML(resultado);           
           }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();        
    } catch (Exception e) {
        e.printStackTrace();
    }

    return xmlCep;
}
    
06.10.2014 в 22:59
11

If you are developing in JavaScript, you can use the following request, http://cep.correiocontrol.com.br/CEP.json , which returns a JSON with the following information:

{
    bairro: "Tijuca",
    logradouro: "Rua Garibaldi",
    cep: "20511330",
    uf: "RJ",
    localidade: "Rio de Janeiro"
}

In the example above:

  

link

    
10.04.2014 в 03:41
10

It is not a service provided by the Post Office, but, as already mentioned, Aviso Brasil provides a free service consultation. It is very simple to use.

For example, link , returns the following string JSON:

  

"" "" "" "" "" "" "" "" "" "" "" "" "" "" " "

    
23.09.2014 в 20:53
9

Another option is to use the postal URL itself.

e.g. In Java using JSOUP that makes it much easier in this case because it is HTML return.

package net.s4bdigital.test.main;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;

import java.io.IOException;
import java.net.URL;
import java.util.Date;

/**
 * Created by eduardo on 03/10/2014.
 */
public class TesteConsultaCEPJSoup {

    @Test
    public void ConsultaCepCorreios(){

        try {

            String urlCorreios = "http://m.correios.com.br/movel/buscaCepConfirma.do";

            Document doc = Jsoup.connect(urlCorreios)
                    .data("cepEntrada", "03582060")
                    .data("tipoCep", "")
                    .data("cepTemp", "")
                    .data("metodo", "buscarCep")
                    // and other hidden fields which are being passed in post request.
                    .userAgent("Mozilla")
                    .post();

            Elements campos = doc.select(".resposta");
            Elements valores = doc.select(".respostadestaque");

            for(int i=0; i < campos.size(); i++){
                Element campo = campos.get(i);
                Element valor = valores.get(i);
                if(campos.hasText() && valores.hasText()){
                    System.out.println(campo.text().trim() + ":" + valor.text().trim());
                }

            }



        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
    
03.10.2014 в 21:06
9

Hello, I use the Post Office Web Service itself. It's simple and free.

The WSDL can be found at: WSDL Post Office

GitHub import and implementation example: GitHub

Video Explicit: Youtube

    
18.05.2016 в 13:11
8

The site ByJG also provides free of charge your CEP's registration through a WebService:

  

The CEP Consultation Service is free to use. It currently works with the post office ZIP code base and contains more than 926,000 sites corresponding to the base of October 2013 (Updated 06/11/2013).

More details on how to use WebService at this address .

    
17.01.2014 в 20:49
4

You can use WebApi below to find the details of a zip code: link

Example: link

It is true that this API is not official of the post office, but the data is updated because the API works as follows:

The API makes a web request on the link link. When doing this, an HTML response is received, the API handles the returned html to extract the address information, and returns the data in JSON format.

    
26.02.2016 в 19:40
2

You do not need to PAY for access to this content. There is a free group that updates the postal code base for free.

Another thing: It is somehow illegal to restrict access to this information.

This is the best current database: link

I have already compared the DVDs sold at the Post Office and this database always has some more and more recent data. Therefore, their access should be almost instantaneous when compared to the old updates sold on DVD.

    
22.02.2016 в 13:50
1

If you need your own base, whether for legal or performance purposes, you can look for some importers.

And a e-DNE incremental import implementation from the delimited TXT files:

  

Place the e-DNE files without changing the original names in the Data folder:

eDNE_Delta_Master_1611.zip
eDNE_Delta_Master_1612.zip
eDNE_Delta_Master_1701.zip
eDNE_Delta_Master_1702.zip
eDNE_Delta_Master_1703.zip
eDNE_Delta_Master_1704.zip
eDNE_Master_1611.zip
     

Run the program stating the connection to the database:

dotnet run "Server=Servidor;Database=Banco;User Id=Usuario;Password=Senha;"
    
22.12.2017 в 11:05
0

You can have your own database for querying zip code and addresses. The qualocep.com is a good zip database and they are always updating. It has in various formats too.

    
31.08.2015 в 15:07