Main Class
Scanner scanner = new Scanner(System.in);
System.out.println("Digite o usuário: ");
var username = scanner.next();
String address = "https://api.github.com/users/" + username;
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(address))
.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(usuarioGitHub);
} catch (ErroConsultaGitHubException s) {
System.out.println(s.getMensagem());
}
}
}
Classe Usuario:
public class Usuario {
private String name;
private String id;
@Override
public String toString() {
return "Usuario{" +
"name='" + name + '\'' +
", id='" + id + '\'' +
'}';
}
}
Classe UsuarioGitHub:
public record UsuarioGitHub(String login, String id) {
}
Console:
/Users/marcos/Library/Java/JavaVirtualMachines/corretto-21.0.2/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA CE.app/Contents/lib/idea_rt.jar=50080:/Applications/IntelliJ IDEA CE.app/Contents/bin -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -classpath /Users/marcos/Desktop/Linux/Marcos/Programas/treino/out/production/treino:/Users/marcos/Documents/Bibliotecas/gson-2.10.1.jar GitHubUsers
Digite o usuário:
marcosmelodev
{"login":"marcosmelodev","id":111325231,"node_id":"U_kgDOBqKwLw","avatar_url":"https://avatars.githubusercontent.com/u/111325231?v=4","gravatar_id":"","url":"https://api.github.com/users/marcosmelodev","html_url":"https://github.com/marcosmelodev","followers_url":"https://api.github.com/users/marcosmelodev/followers","following_url":"https://api.github.com/users/marcosmelodev/following{/other_user}","gists_url":"https://api.github.com/users/marcosmelodev/gists{/gist_id}","starred_url":"https://api.github.com/users/marcosmelodev/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/marcosmelodev/subscriptions","organizations_url":"https://api.github.com/users/marcosmelodev/orgs","repos_url":"https://api.github.com/users/marcosmelodev/repos","events_url":"https://api.github.com/users/marcosmelodev/events{/privacy}","received_events_url":"https://api.github.com/users/marcosmelodev/received_events","type":"User","site_admin":false,"name":null,"company":null,"blog":"","location":null,"email":null,"hireable":null,"bio":null,"twitter_username":null,"public_repos":9,"public_gists":0,"followers":0,"following":3,"created_at":"2022-08-16T00:48:29Z","updated_at":"2024-04-26T18:50:06Z"}
UsuarioGitHub[login=marcosmelodev, id=111325231]