1
+ import java .io .BufferedReader ;
2
+ import java .io .InputStreamReader ;
3
+ import java .net .HttpURLConnection ;
4
+ import java .net .URL ;
5
+ import java .util .Scanner ;
6
+ import org .json .JSONArray ;
7
+ import org .json .JSONObject ;
8
+
9
+ /**
10
+ * Este programa demuestra el uso de peticiones HTTP en Java y la integración
11
+ * con la PokéAPI.
12
+ *
13
+ * Teoría sobre peticiones HTTP:
14
+ * - HTTP (Hypertext Transfer Protocol) es un protocolo de comunicación que
15
+ * permite
16
+ * la transferencia de información en la World Wide Web.
17
+ * - Los métodos HTTP más comunes son:
18
+ * * GET: Solicita datos de un recurso específico
19
+ * * POST: Envía datos para crear un nuevo recurso
20
+ * * PUT: Actualiza un recurso existente
21
+ * * DELETE: Elimina un recurso
22
+ *
23
+ * En Java, podemos realizar peticiones HTTP utilizando la clase
24
+ * HttpURLConnection,
25
+ * que nos permite establecer una conexión con un servidor web y enviar/recibir
26
+ * datos.
27
+ */
28
+ public class EulogioEP {
29
+ public static void main (String [] args ) {
30
+ Scanner scanner = new Scanner (System .in );
31
+
32
+ // Ejemplo básico de petición HTTP
33
+ System .out .println ("=== Ejemplo básico de petición HTTP ===" );
34
+ try {
35
+ String content = makeHttpRequest ("https://www.example.com" );
36
+ System .out .println ("Contenido de example.com:" );
37
+ System .out .println (content );
38
+ } catch (Exception e ) {
39
+ System .out .println ("Error al realizar la petición HTTP: " + e .getMessage ());
40
+ }
41
+
42
+ // Funcionalidad de la PokéAPI
43
+ while (true ) {
44
+ System .out .println ("\n === Búsqueda de Pokémon ===" );
45
+ System .out .println ("Ingrese el nombre o número del Pokémon (o 'salir' para terminar):" );
46
+ String input = scanner .nextLine ().toLowerCase ();
47
+
48
+ if (input .equals ("salir" )) {
49
+ break ;
50
+ }
51
+
52
+ try {
53
+ // Realizar petición a la PokéAPI
54
+ String pokemonData = makeHttpRequest ("https://pokeapi.co/api/v2/pokemon/" + input );
55
+ JSONObject pokemon = new JSONObject (pokemonData );
56
+
57
+ // Mostrar información básica del Pokémon
58
+ System .out .println ("\n Información del Pokémon:" );
59
+ System .out .println ("Nombre: " + pokemon .getString ("name" ));
60
+ System .out .println ("ID: " + pokemon .getInt ("id" ));
61
+ System .out .println ("Peso: " + pokemon .getInt ("weight" ) / 10.0 + " kg" );
62
+ System .out .println ("Altura: " + pokemon .getInt ("height" ) / 10.0 + " m" );
63
+
64
+ // Mostrar tipos
65
+ System .out .println ("Tipos:" );
66
+ JSONArray types = pokemon .getJSONArray ("types" );
67
+ for (int i = 0 ; i < types .length (); i ++) {
68
+ System .out .println ("- " + types .getJSONObject (i ).getJSONObject ("type" ).getString ("name" ));
69
+ }
70
+
71
+ // Obtener y mostrar cadena de evolución
72
+ String speciesUrl = pokemon .getJSONObject ("species" ).getString ("url" );
73
+ String speciesData = makeHttpRequest (speciesUrl );
74
+ JSONObject species = new JSONObject (speciesData );
75
+ String evolutionChainUrl = species .getJSONObject ("evolution_chain" ).getString ("url" );
76
+ String evolutionData = makeHttpRequest (evolutionChainUrl );
77
+ JSONObject evolution = new JSONObject (evolutionData );
78
+
79
+ System .out .println ("\n Cadena de evolución:" );
80
+ printEvolutionChain (evolution .getJSONObject ("chain" ));
81
+
82
+ // Mostrar juegos
83
+ System .out .println ("\n Juegos en los que aparece:" );
84
+ JSONArray games = pokemon .getJSONArray ("game_indices" );
85
+ for (int i = 0 ; i < games .length (); i ++) {
86
+ System .out .println ("- " + games .getJSONObject (i ).getJSONObject ("version" ).getString ("name" ));
87
+ }
88
+
89
+ } catch (Exception e ) {
90
+ System .out .println (
91
+ "Error: No se pudo encontrar el Pokémon. Asegúrese de escribir el nombre o número correctamente." );
92
+ }
93
+ }
94
+
95
+ scanner .close ();
96
+ }
97
+
98
+ /**
99
+ * Realiza una petición HTTP GET a la URL especificada.
100
+ *
101
+ * @param urlString La URL a la que se realizará la petición
102
+ * @return El contenido de la respuesta como String
103
+ * @throws Exception Si ocurre un error durante la petición
104
+ */
105
+ private static String makeHttpRequest (String urlString ) throws Exception {
106
+ URL url = new URL (urlString );
107
+ HttpURLConnection conn = (HttpURLConnection ) url .openConnection ();
108
+ conn .setRequestMethod ("GET" );
109
+
110
+ if (conn .getResponseCode () != 200 ) {
111
+ throw new RuntimeException ("HTTP error code : " + conn .getResponseCode ());
112
+ }
113
+
114
+ BufferedReader br = new BufferedReader (new InputStreamReader ((conn .getInputStream ())));
115
+ StringBuilder response = new StringBuilder ();
116
+ String output ;
117
+ while ((output = br .readLine ()) != null ) {
118
+ response .append (output );
119
+ }
120
+ conn .disconnect ();
121
+
122
+ return response .toString ();
123
+ }
124
+
125
+ /**
126
+ * Imprime recursivamente la cadena de evolución de un Pokémon.
127
+ *
128
+ * @param chain El objeto JSON que contiene la información de la cadena de
129
+ * evolución
130
+ */
131
+ private static void printEvolutionChain (JSONObject chain ) {
132
+ String pokemonName = chain .getJSONObject ("species" ).getString ("name" );
133
+ System .out .println ("- " + pokemonName );
134
+
135
+ JSONArray evolvesTo = chain .getJSONArray ("evolves_to" );
136
+ for (int i = 0 ; i < evolvesTo .length (); i ++) {
137
+ printEvolutionChain (evolvesTo .getJSONObject (i ));
138
+ }
139
+ }
140
+ }
0 commit comments