Skip to content

Commit 4440637

Browse files
committed
#20 - Java
1 parent 56d6b4c commit 4440637

File tree

1 file changed

+239
-0
lines changed

1 file changed

+239
-0
lines changed
Lines changed: 239 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,239 @@
1+
/*
2+
* EJERCICIO:
3+
* Utilizando un mecanismo de peticiones HTTP de tu lenguaje, realiza
4+
* una petición a la web que tú quieras, verifica que dicha petición
5+
* fue exitosa y muestra por consola el contenido de la web.
6+
*
7+
* DIFICULTAD EXTRA (opcional):
8+
* Utilizando la PokéAPI (https://pokeapi.co), crea un programa por
9+
* terminal al que le puedas solicitar información de un Pokémon concreto
10+
* utilizando su nombre o número.
11+
* - Muestra el nombre, id, peso, altura y tipo(s) del Pokémon
12+
* - Muestra el nombre de su cadena de evoluciones
13+
* - Muestra los juegos en los que aparece
14+
* - Controla posibles errores
15+
*/
16+
17+
import java.io.IOException;
18+
import java.net.URI;
19+
import java.net.http.HttpClient;
20+
import java.net.http.HttpRequest;
21+
import java.net.http.HttpResponse;
22+
import java.util.Scanner;
23+
24+
public class JimsimroDev {
25+
private static final String URL_BASE = "https://pokeapi.co/api/v2/pokemon/";
26+
27+
String consumirApi(String url) {
28+
HttpClient client = HttpClient.newHttpClient();
29+
HttpRequest request = HttpRequest.newBuilder()
30+
.uri(URI.create(url))
31+
.build();
32+
HttpResponse<String> response = null;
33+
34+
try {
35+
response = client.send(request, HttpResponse.BodyHandlers.ofString());
36+
} catch (IOException e) {
37+
throw new RuntimeException(e);
38+
} catch (InterruptedException e) {
39+
throw new RuntimeException(e);
40+
}
41+
if (response.statusCode() == 200) {
42+
IO.println("Respuesta exitosa codigo: " + response.statusCode());
43+
String json = response.body();
44+
return json;
45+
}
46+
throw new RuntimeException("Eror al procesar la solicitud codigo de error " + response.statusCode());
47+
}
48+
49+
// Busca campo en la Raiz
50+
private String getCampo(StringBuilder data, String campo) {
51+
String patron = "\"" + campo + "\":";
52+
int inicio = data.indexOf(patron);
53+
if (inicio != -1) {
54+
inicio += patron.length();
55+
while (inicio < data.length() && Character.isWhitespace(data.charAt(inicio))) {
56+
inicio++;
57+
}
58+
if (inicio < data.length()) {
59+
if (data.charAt(inicio) == '"') {
60+
inicio++;
61+
int fin = data.indexOf("\"", inicio);
62+
if (fin != -1) {
63+
return data.substring(inicio, fin);
64+
}
65+
} else {
66+
int fin = inicio;
67+
while (fin < data.length() &&
68+
data.charAt(fin) != ',' &&
69+
data.charAt(fin) != '}' &&
70+
data.charAt(fin) != '\n') {
71+
fin++;
72+
}
73+
return data.substring(inicio, fin).trim();
74+
}
75+
}
76+
}
77+
return null;
78+
}
79+
80+
// Busca campo en una sección dada
81+
private String getCampo(StringBuilder data, String seccion, String campo) {
82+
int indiceSeccion = data.indexOf("\"" + seccion + "\"");
83+
if (indiceSeccion != -1) {
84+
String patron = "\"" + campo + "\":\"";
85+
int indiceCampo = data.indexOf(patron, indiceSeccion);
86+
87+
if (indiceCampo != -1) {
88+
int empiezaValor = indiceCampo + patron.length();
89+
int terminaValor = data.indexOf("\"", empiezaValor);
90+
return data.substring(empiezaValor, terminaValor);
91+
}
92+
}
93+
return null;
94+
}
95+
96+
// Busca los typos
97+
private String[] getTypes(StringBuilder data) {
98+
String tiposPattern = "\"types\":[";
99+
int startIndex = data.indexOf(tiposPattern);
100+
if (startIndex != -1) {
101+
startIndex += tiposPattern.length();
102+
int endIdex = data.indexOf("]", startIndex);
103+
if (endIdex != -1) {
104+
String tiposArray = data.substring(startIndex, endIdex);
105+
String[] tipos = tiposArray.split("},");
106+
String[] resultados = new String[tipos.length];
107+
// Procesar cada tipo
108+
for (int i = 0; i < tipos.length; i++) {
109+
String tipo = tipos[i];
110+
String namePattern = "\"name\":\"";
111+
int nameStart = tipo.indexOf(namePattern);
112+
if (nameStart != -1) {
113+
nameStart += namePattern.length();
114+
int nameEnd = tipo.indexOf("\"", nameStart);
115+
if (nameEnd != -1) {
116+
resultados[i] = tipo.substring(nameStart, nameEnd);
117+
}
118+
}
119+
}
120+
return resultados;
121+
}
122+
}
123+
return new String[0];
124+
}
125+
126+
private String getEvolutionChainUrl(StringBuilder data) {
127+
String patron = "\"evolution_chain\":{\"url\":\"";
128+
int inicio = data.indexOf(patron);
129+
if (inicio != -1) {
130+
inicio += patron.length();
131+
int fin = data.indexOf("\"", inicio);
132+
if (fin != -1) {
133+
return data.substring(inicio, fin);
134+
}
135+
}
136+
return null;
137+
}
138+
139+
void evolution_chain(StringBuilder data) {
140+
// Obtener el nombre de la especie actual
141+
String speciesName = getCampo(data, "species", "name");
142+
IO.println("Evolución: " + speciesName);
143+
144+
// Buscar el patrón de evolves_to
145+
String evolvesToPattern = "\"evolves_to\":[";
146+
int evolvesToIndex = data.indexOf(evolvesToPattern);
147+
148+
if (evolvesToIndex != -1) {
149+
// Si encontramos evolves_to y no está vacío
150+
evolvesToIndex += evolvesToPattern.length();
151+
if (data.charAt(evolvesToIndex) != ']') {
152+
// Obtener el contenido del evolves_to
153+
int endIndex = findMatchingBracket(data, evolvesToIndex);
154+
if (endIndex != -1) {
155+
// Crear un nuevo StringBuilder con el contenido de evolves_to
156+
StringBuilder evolvesTo = new StringBuilder(
157+
data.substring(evolvesToIndex, endIndex));
158+
// Llamada recursiva con el nuevo contenido
159+
evolution_chain(evolvesTo);
160+
}
161+
}
162+
}
163+
}
164+
165+
// Método auxiliar para encontrar el corchete de cierre correspondiente
166+
private int findMatchingBracket(StringBuilder data, int startIndex) {
167+
int count = 1;
168+
for (int i = startIndex; i < data.length(); i++) {
169+
if (data.charAt(i) == '[')
170+
count++;
171+
if (data.charAt(i) == ']')
172+
count--;
173+
if (count == 0)
174+
return i;
175+
}
176+
return -1;
177+
}
178+
179+
void main() {
180+
Scanner in = new Scanner(System.in);
181+
182+
// HttpClient client = HttpClient.newHttpClient();
183+
//
184+
// HttpRequest request = HttpRequest.newBuilder()
185+
// .uri(URI.create("https://www.mercadolibre.com.co/"))
186+
// .build();
187+
// HttpResponse<String> response = null;
188+
//
189+
// try {
190+
// response = client.send(request, HttpResponse.BodyHandlers.ofString());
191+
// } catch (IOException e) {
192+
// throw new RuntimeException(e);
193+
// } catch (InterruptedException e) {
194+
// throw new RuntimeException(e);
195+
// }
196+
// String json = response.body();
197+
// IO.println("Estado " + response.statusCode());
198+
// IO.println(json);
199+
200+
IO.println("Ingresa el nombre del pokemon a consultar");
201+
String pokemon = in.nextLine();
202+
203+
StringBuilder data = new StringBuilder();
204+
StringBuilder url = new StringBuilder();
205+
206+
data.append(consumirApi(URL_BASE + pokemon));
207+
208+
String nombre = getCampo(data, "name");
209+
210+
String id = getCampo(data, "id");
211+
212+
String peso = getCampo(data, "weight");
213+
214+
String altura = getCampo(data, "height");
215+
String[] tipos = getTypes(data);
216+
217+
String urlSpecies = getCampo(data, "species", "url");
218+
219+
url.append(consumirApi(urlSpecies));
220+
String urlEvolucion = getEvolutionChainUrl(url);
221+
222+
// StringBuilder evolution = new StringBuilder();
223+
// String evolucin = getCampo(evolution, "species", "name");
224+
// IO.println("url evloucion " + evolution);
225+
// IO.println("evolution" + evolucin);
226+
227+
StringBuilder evolutionData = new StringBuilder(consumirApi(urlEvolucion));
228+
evolution_chain(evolutionData);
229+
IO.println("Nombre: " + nombre);
230+
IO.println("ID: " + id);
231+
IO.println("Peso: " + peso);
232+
IO.println("Altura: " + altura);
233+
IO.println("Tipos:");
234+
for (String tipo : tipos) {
235+
IO.println("- " + tipo);
236+
}
237+
in.close();
238+
}
239+
}

0 commit comments

Comments
 (0)