package br.com.alura.screenmatch.principal;
import br.com.alura.screenmatch.excecao.ErroConsultaGitHubException;
import br.com.alura.screenmatch.modelos.Usuario;
import br.com.alura.screenmatch.modelos.UsuarioGitHub;
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;
import java.util.Scanner;
public class DesafioConsultaGitHub {
public static void main(String[] args) {
Scanner leitura = new Scanner(System.in);
System.out.println("Insira o nome do usuário: ");
String nomeUsuario = leitura.nextLine();
String endereco = "https://api.github.com/users/" + nomeUsuario;
try{
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(endereco))
.header("Accept", "application/vnd.github.v3+json")
.build();
HttpResponse<String> response = client
.send(request, HttpResponse.BodyHandlers.ofString());
if(response.statusCode() == 404){
throw new ErroConsultaGitHubException("Usuário não encontrado. ");
}
String json = response.body();
System.out.println(json);
Gson gson = new GsonBuilder().create();
UsuarioGitHub usuarioGitHub = gson.fromJson(json, UsuarioGitHub.class);
System.out.println("\nUsuário GitHub: " + usuarioGitHub);
Usuario usuario = new Usuario(usuarioGitHub);
System.out.println("\nUsuário: " + usuario);
} catch (IOException | InterruptedException e) {
System.out.println("Houve um erro na consulta da API do GitHub.");
e.printStackTrace();
}catch (ErroConsultaGitHubException e) {
System.out.println(e.getMessage());
}finally {
System.out.println("\nConsulta Finalizada!");
}
}
}
package br.com.alura.screenmatch.modelos;
public class Usuario {
private String nomeUsuario;
private String id;
public Usuario(UsuarioGitHub usuarioGitHub){
this.nomeUsuario = usuarioGitHub.login();
this.id = String.valueOf(usuarioGitHub.id());
}
@Override
public String toString() {
return "Nome: " + nomeUsuario + "\nid: " + id;
}
}
package br.com.alura.screenmatch.modelos;
public record UsuarioGitHub(String login, int id) {
}
public class ErroConsultaGitHubException extends RuntimeException {
public ErroConsultaGitHubException(String mensagem){
super(mensagem);
}
}