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 Buscador {
public Endereco busca(String cep) {
String endereco = "https://viacep.com.br/ws/" + cep + "/json/";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(endereco))
.build();
HttpResponse<String> response = null;
try {
response = client
.send(request, HttpResponse.BodyHandlers.ofString());
return new Gson().fromJson(response.body(),Endereco.class);
} catch (IOException | InterruptedException e) {
throw new RuntimeException("ouve um erro pra encontrar o endereço declarado");
}
}
}
public record Endereco(String cep, String logradouro,String uf,String bairro, String complemento,String localidade) {
}
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.FileWriter;
import java.io.IOException;
public class GerandoArquivo {
public void gerador(Endereco endereco) throws IOException {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
FileWriter fileWriter = new FileWriter(endereco.cep()+".json");
fileWriter.write(gson.toJson(endereco));
fileWriter.close();
}
}
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
String cep = "";
while (!cep.equalsIgnoreCase("sair")){
System.out.println("digite um cep ou sair para finalizar");
cep = sc.nextLine();
try {
Buscador buscador = new Buscador();
Endereco endereco = buscador.busca(cep);
System.out.println(endereco);
GerandoArquivo gerandoArquivo = new GerandoArquivo();
gerandoArquivo.gerador(endereco);
} catch (RuntimeException e) {
System.out.println("programa finalizado");
}
}
sc.close();
}
}