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)?
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)?
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 ).
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 .
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.");
}
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');
}
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
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>
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.
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"}
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;
}
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:
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:
"" "" "" "" "" "" "" "" "" "" "" "" "" "" " "
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();
}
}
}
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
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 .
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.
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.
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.zipRun the program stating the connection to the database:
dotnet run "Server=Servidor;Database=Banco;User Id=Usuario;Password=Senha;"
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.