Last active
March 17, 2020 17:54
-
-
Save DeveloperArthur/518b3ce5e425b7cc10ad1a92d235c591 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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