Essa foi minha solução do desafio, tentei utilizar grande parte dos conceitos visto até então na formação, também tentei organizar grande parte do código em pacotes com suas principais responsabilidades.
código no github:
https://github.com/Gabriel-Labritz/viacepdesafio
Main:
package br.com.desafioapibuscaporcep;
import br.com.desafioapibuscaporcep.entities.Address;
import br.com.desafioapibuscaporcep.services.ApiCepService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ApiCepService service = new ApiCepService();
System.out.print("Informe o cep para busca: ");
String cep = scanner.nextLine();
Address address = service.getAddress(cep);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String addressJson = gson.toJson(address);
try {
FileWriter writer = new FileWriter("address.json");
writer.write(addressJson);
writer.close();
} catch (FileNotFoundException e) {
System.out.println("Erro ao encontrar o arquivo: " + e.getMessage());
} catch (IOException e) {
System.out.println("Erro na escrita do arquivo: " + e.getMessage());
}
}
}
ApiCepService:
package br.com.desafioapibuscaporcep.services;
import br.com.desafioapibuscaporcep.dtos.ViaCepAddress;
import br.com.desafioapibuscaporcep.entities.Address;
import br.com.desafioapibuscaporcep.exceptions.CepFormatException;
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 ApiCepService {
private Address address;
public Address getAddress(String cep) {
String searchCep = cep.replace(" ", "").trim();
String baseUrl = "https://viacep.com.br/ws/".concat(searchCep).concat("/json");
try {
if (searchCep.length() > 8) {
throw new CepFormatException("O formato do cep fornecido é inválido");
}
HttpClient client = HttpClient.newHttpClient();
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create(baseUrl))
.build();
HttpResponse<String> res = client.send(req, HttpResponse.BodyHandlers.ofString());
String json = res.body();
Gson gson = new Gson();
ViaCepAddress viaCepAddress = gson.fromJson(json, ViaCepAddress.class);
this.address = new Address(viaCepAddress);
} catch (CepFormatException e) {
System.out.println(e.getMessage());
} catch (IOException | InterruptedException e) {
System.out.println(e.getMessage());
}
return this.address;
}
}
ViaCepAddress:
package br.com.desafioapibuscaporcep.dtos;
public record ViaCepAddress
(String cep,
String logradouro,
String bairro,
String localidade,
String uf
) {
}
Address:
package br.com.desafioapibuscaporcep.entities;
import br.com.desafioapibuscaporcep.dtos.ViaCepAddress;
public class Address {
private String cep;
private String street;
private String neighborhood;
private String city;
private String uf;
public Address (ViaCepAddress viaCepAddress) {
this.cep = viaCepAddress.cep();
this.street = viaCepAddress.logradouro();
this.neighborhood = viaCepAddress.bairro();
this.city = viaCepAddress.localidade();
this.uf = viaCepAddress.uf();
}
public String getCep() {
return cep;
}
public String getStreet() {
return street;
}
public String getNeighborhood() {
return neighborhood;
}
public String getCity() {
return city;
}
public String getUf() {
return uf;
}
@Override
public String toString() {
return "Cep: " + this.getCep()
+ " Rua: " + this.getStreet()
+ " Bairro: " + this.getNeighborhood()
+ " Cidade: " + this.getCity()
+ " UF: " + this.getUf();
}
}
CepFormatException:
package br.com.desafioapibuscaporcep.exceptions;
public class CepFormatException extends RuntimeException {
public CepFormatException(String message) {
super(message);
}
}
arquivo address.json:
{
"cep": "01001-000",
"street": "Praça da Sé",
"neighborhood": "Sé",
"city": "São Paulo",
"uf": "SP"
}