ConsumoApi.java
package br.com.alura.tabelafipe.tabela_fipe.model;
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.NoSuchElementException;
public class ConsumoApi {
public String consumir(String endereco){
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());
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
String json = response.body();
if(json.contains("error")) {throw new NoSuchElementException("Ocorreu um erro na api, verifique seus inputs");
}
return json;
}
}
DadosRecebidos.java
package br.com.alura.tabelafipe.tabela_fipe.model;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public record DadosRecebidos(
@JsonAlias("codigo") String codigo,
@JsonAlias("nome") String descricao
) {
@Override
public String toString() {
return "Cód: " +this.codigo+" \tDescrição: "+this.descricao;
}
}
ListaModelos.java
package br.com.alura.tabelafipe.tabela_fipe.model;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true)
public record ListaModelos(
@JsonAlias("modelos") List<DadosRecebidos> modelos
) {
}