Skip to content

Commit df64c0b

Browse files
committed
#20 - Java
1 parent ab02a34 commit df64c0b

File tree

1 file changed

+126
-0
lines changed

1 file changed

+126
-0
lines changed
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
package dev.asjordi.r20;
2+
3+
import com.google.gson.Gson;
4+
import com.google.gson.JsonObject;
5+
import java.net.URI;
6+
import java.net.http.HttpClient;
7+
import java.net.http.HttpRequest;
8+
import java.net.http.HttpResponse;
9+
import java.util.Scanner;
10+
11+
public class Main {
12+
13+
public static void main(String[] args) throws Exception {
14+
getRequest("https://www.google.com");
15+
getPokemon();
16+
}
17+
18+
/**
19+
* EJERCICIO:
20+
* Utilizando un mecanismo de peticiones HTTP de tu lenguaje, realiza
21+
* una petición a la web que tú quieras, verifica que dicha petición
22+
* fue exitosa y muestra por consola el contenido de la web.
23+
*/
24+
public static void getRequest(String url) throws Exception {
25+
HttpClient client = HttpClient.newHttpClient();
26+
HttpRequest request = HttpRequest.newBuilder()
27+
.uri(URI.create(url))
28+
.build();
29+
30+
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
31+
32+
if (response.statusCode() != 200) throw new Exception("Request failed with status code: " + response.statusCode());
33+
else System.out.println(response.body());
34+
}
35+
36+
/**
37+
* DIFICULTAD EXTRA (opcional):
38+
* Utilizando la PokéAPI (https://pokeapi.co), crea un programa por
39+
* terminal al que le puedas solicitar información de un Pokémon concreto
40+
* utilizando su nombre o número.
41+
* - Muestra el nombre, id, peso, altura y tipo(s) del Pokémon
42+
* - Muestra el nombre de su cadena de evoluciones
43+
* - Muestra los juegos en los que aparece
44+
* - Controla posibles errores
45+
*/
46+
public static void getPokemon() {
47+
Scanner sc = new Scanner(System.in);
48+
Gson gson = new Gson();
49+
50+
System.out.println("Introduce el nombre o número del Pokémon:");
51+
String param = sc.nextLine();
52+
53+
String baseUrl = String.format("https://pokeapi.co/api/v2/pokemon/%s", param);
54+
var getBaseResponse = sendRequest(baseUrl);
55+
if (getBaseResponse.statusCode() != 200) System.out.println("Error: " + getBaseResponse.statusCode());
56+
String baseResponseBody = getBaseResponse.body();
57+
JsonObject data = gson.fromJson(baseResponseBody, JsonObject.class);
58+
59+
String id = data.get("id").getAsString();
60+
String name = data.get("name").getAsString();
61+
String weight = data.get("weight").getAsString();
62+
String height = data.get("height").getAsString();
63+
64+
String chainUrl = String.format("https://pokeapi.co/api/v2/evolution-chain/%s", id);
65+
var getChainResponse = sendRequest(chainUrl);
66+
if (getChainResponse.statusCode() != 200) System.out.println("Error: " + getChainResponse.statusCode());
67+
String chainResponseBody = getChainResponse.body();
68+
JsonObject chainData = gson.fromJson(chainResponseBody, JsonObject.class);
69+
70+
var types = data.getAsJsonArray("types");
71+
StringBuilder typeNames = new StringBuilder();
72+
for (int i = 0; i < types.size(); i++) {
73+
JsonObject type = types.get(i).getAsJsonObject().getAsJsonObject("type");
74+
typeNames.append(type.get("name").getAsString());
75+
if (i < types.size() - 1) typeNames.append(", ");
76+
}
77+
78+
var gameIndices = data.getAsJsonArray("game_indices");
79+
StringBuilder gameNames = new StringBuilder();
80+
for (int i = 0; i < gameIndices.size(); i++) {
81+
JsonObject game = gameIndices.get(i).getAsJsonObject().getAsJsonObject("version");
82+
gameNames.append(game.get("name").getAsString());
83+
if (i < gameIndices.size() - 1) gameNames.append(", ");
84+
}
85+
86+
var chain = chainData.getAsJsonObject("chain");
87+
StringBuilder evolutionNames = new StringBuilder();
88+
getEvolutions(chain, evolutionNames);
89+
90+
System.out.println("ID: " + id);
91+
System.out.println("Nombre: " + name);
92+
System.out.println("Peso: " + weight);
93+
System.out.println("Altura: " + height);
94+
System.out.println("Tipos: " + typeNames.toString());
95+
System.out.println("Las evoluciones de " + name + " son: " + evolutionNames.toString());
96+
System.out.println("Aparece en los juegos: " + gameNames.toString());
97+
}
98+
99+
private static void getEvolutions(JsonObject chain, StringBuilder evolutionNames) {
100+
String chainName = chain.getAsJsonObject("species").get("name").getAsString();
101+
evolutionNames.append(chainName);
102+
103+
var evolutions = chain.getAsJsonArray("evolves_to");
104+
for (int i = 0; i < evolutions.size(); i++) {
105+
evolutionNames.append(" -> ");
106+
getEvolutions(evolutions.get(i).getAsJsonObject(), evolutionNames);
107+
}
108+
}
109+
110+
private static HttpResponse<String> sendRequest(String url) {
111+
HttpClient client = HttpClient.newHttpClient();
112+
HttpRequest getRequest = HttpRequest.newBuilder()
113+
.uri(URI.create(url))
114+
.GET()
115+
.build();
116+
HttpResponse<String> getResponse = null;
117+
118+
try {
119+
getResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString());
120+
} catch (Exception e) {
121+
System.out.println("Error: " + e.getMessage());
122+
}
123+
124+
return getResponse;
125+
}
126+
}

0 commit comments

Comments
 (0)