package br.com.alura.buscadorDeCEP;
import java.io.IOException;
import java.util.*;
public class Principal {
public static void main(String[] args) throws IOException, InterruptedException {
Scanner scan = new Scanner(System.in);
ConsultaCEP consulta = new ConsultaCEP();
String cep = "";
Endereco novaBusca = null;
List<Endereco> listaDeEnderecos = new ArrayList<>();
String message = "Digite o cep que deseja buscar ou digite SAIR para parar: ";
System.out.println(message);
cep = scan.nextLine();
while (!cep.equalsIgnoreCase("SAIR")){
try {
novaBusca = consulta.buscaEndereco(cep);
listaDeEnderecos.add(novaBusca);
System.out.println(message);
cep = scan.nextLine();
GeradorDeArquivo gerador = new GeradorDeArquivo();
gerador.geraArquivoJson(listaDeEnderecos);
} catch (RuntimeException e) {
System.out.println(e.getMessage());
break;
}
}
System.out.println(listaDeEnderecos);
scan.close();
}
}
package br.com.alura.buscadorDeCEP;
public record Endereco(String cep, String logradouro, String bairro, String localidade, String uf) {
}
package br.com.alura.buscadorDeCEP;
import com.google.gson.Gson;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class ConsultaCEP {
public Endereco buscaEndereco(String cep) {
URI enderecoBusca = URI.create("http://viacep.com.br/ws/" + cep + "/json");
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(enderecoBusca)
.build();
try {
HttpResponse<String> response = client
.send(request, HttpResponse.BodyHandlers.ofString());
return new Gson().fromJson(response.body(), Endereco.class);
} catch (Exception e) {
throw new RuntimeException("Não consegui encontrar o endereço", e);
}
}
}
package br.com.alura.buscadorDeCEP;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
public class GeradorDeArquivo {
public void geraArquivoJson(List<Endereco> endereco) throws IOException {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
FileWriter file = new FileWriter("endereco.json");
file.write(gson.toJson(endereco));
file.close();
}
}