Segui o que a professora sugeriu:
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner readingCep = new Scanner(System.in);
QueryCep queryCep = new QueryCep();
System.out.println("Consulte o CEP: ");
var newCep = readingCep.nextLine();
try{
Address newAddres = queryCep.searchingAddress(newCep);
System.out.println(newAddres);
CreateFiles createFiles = new CreateFiles();
createFiles.jsonFiles(newAddres);
}catch (RuntimeException | IOException e){
System.out.println(e.getMessage());
System.out.println("Finalizando a aplicação.");
}
}
}
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.FileWriter;
import java.io.IOException;
public class CreateFiles {
public void jsonFiles(Address address) throws IOException {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
FileWriter writing = new FileWriter(address.cep() + ".json");
writing.write(gson.toJson(address));
writing.close();
}
}
public record Address(String cep, String logradouro, String complemento, String bairro, String localidade, String uf) {
}
import com.google.gson.Gson;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class QueryCep {
public Address searchingAddress(String cep){
URI address = URI.create("https://viacep.com.br/ws/" + cep + "/json/");
HttpRequest request = HttpRequest.newBuilder()
.uri(address)
.build();
try {
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
return new Gson().fromJson(response.body(), Address.class);
} catch (Exception e) {
throw new RuntimeException("O endereço não foi identificado.");
}
}
}
Espero que possa ajudar alguém <3