import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
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 endereco = URI.create("https://viacep.com.br/ws/" + cep + "/json");
HttpRequest request = HttpRequest.newBuilder()
.uri(endereco)
.build();
try {
HttpResponse<String> response = HttpClient
.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
return new Gson().fromJson(response.body(), Endereco.class);
} catch (Exception e) {
throw new RuntimeException("Endereço não encontrado!");
}
}
}
public record Endereco(String cep, String logradouro, String complemento, String localidade, String uf) {
}
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.FileWriter;
import java.io.IOException;
public class GeradorDeArquivo {
public void salvaJson(Endereco endereco) throws IOException {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
FileWriter escrita = new FileWriter(endereco.cep() + ".json");
escrita.write(gson.toJson(endereco));
escrita.close();
}
}
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ConsultaCep consultaCep = new ConsultaCep();
System.out.println("Digite o CEP: ");
String cep = scanner.nextLine();
try {
Endereco novoEndereco = consultaCep.buscaEndereco(cep);
System.out.println(novoEndereco);
GeradorDeArquivo gerador = new GeradorDeArquivo();
gerador.salvaJson(novoEndereco);
} catch (RuntimeException | IOException e) {
System.out.println(e.getMessage());
System.out.println("Fim");
}
}
}