Skip to content

Instantly share code, notes, and snippets.

@DeveloperArthur
Last active March 17, 2020 17:54
Show Gist options
  • Save DeveloperArthur/518b3ce5e425b7cc10ad1a92d235c591 to your computer and use it in GitHub Desktop.
Save DeveloperArthur/518b3ce5e425b7cc10ad1a92d235c591 to your computer and use it in GitHub Desktop.
package br.com.meubuscadordecep.viacep;
import br.com.meubuscadordecep.Util;
import br.com.meubuscadordecep.dominio.Endereco;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ServicoDeCep {
static String webService = "http://viacep.com.br/ws/";
static int codigoSucesso = 200;
public static Endereco buscaEnderecoPelo(String cep) throws Exception {
String urlParaChamada = webService + cep + "/json";
try {
URL url = new URL(urlParaChamada);
HttpURLConnection conexao = (HttpURLConnection) url.openConnection();
if (conexao.getResponseCode() != codigoSucesso)
throw new RuntimeException("HTTP error code : " + conexao.getResponseCode());
BufferedReader resposta = new BufferedReader(new InputStreamReader((conexao.getInputStream())));
String jsonEmString = Util.converteJsonEmString(resposta);
Gson gson = new Gson();
Endereco endereco = gson.fromJson(jsonEmString, Endereco.class);
return endereco;
} catch (Exception e) {
throw new Exception("ERRO: " + e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment