#
package api;
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;
import java.util.Scanner;
public class Api {
public Endereco buscarApi( String busca) {
try {
String endereco = "https://viacep.com.br/ws/" + busca + "/json/";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(endereco)).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
String json =response.body();
System.out.println(json);
return new Gson().fromJson(response.body(),Endereco.class);
}catch (IOException e){
System.out.println("erro" + e.getMessage());
}catch (InterruptedException e){
System.out.println("erro: "+ e.getMessage());
}
return null;
}
}
#
package api;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.FileWriter;
import java.io.IOException;
public class GeradorDeArquivo {
public void geraJson(Endereco endereco) {
try {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
FileWriter escrita = new FileWriter("Endereco.json");
escrita.write(gson.toJson(endereco));
escrita.close();
}catch (IOException e){
System.out.println("erro "+ e.getMessage());
}
}
}
package api;
public record Endereco(String logradouro,String cep,String localidade, String complemento) {
}
#
import api.Api;
import api.Endereco;
import api.GeradorDeArquivo;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Api api = new Api();
Scanner leitura = new Scanner(System.in);
System.out.println("Digite um numero de cep");
String busca = leitura.nextLine();
Endereco novoEndereco =api.buscarApi(busca);
GeradorDeArquivo gerador = new GeradorDeArquivo();
gerador.geraJson(novoEndereco);
}
}