Skip to content

Commit b5862de

Browse files
committed
#20 - Kotlin
1 parent f5b9bf7 commit b5862de

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import io.ktor.client.HttpClient
2+
import io.ktor.client.call.body
3+
import io.ktor.client.request.get
4+
import io.ktor.client.statement.HttpResponse
5+
import io.ktor.client.statement.bodyAsText
6+
import io.ktor.http.ContentType
7+
import io.ktor.http.HttpStatusCode
8+
import io.ktor.http.contentType
9+
10+
suspend fun main() {
11+
// Petición HTTP a una página web
12+
val client = HttpClient()
13+
val response: HttpResponse = client.get("https://www.example.com")
14+
15+
if (response.status == HttpStatusCode.OK) {
16+
println("Petición exitosa, contenido de la web:")
17+
println(response.bodyAsText())
18+
} else {
19+
println("Error en la petición: ${response.status}")
20+
}
21+
22+
// Consulta de información de un Pokémon a través de la PokéAPI
23+
println("\nConsulta de información de un Pokémon:")
24+
val pokemonName = "pikachu"
25+
val pokemonInfo = getPokemonInfo(pokemonName)
26+
27+
println("Nombre: ${pokemonInfo.name}")
28+
println("ID: ${pokemonInfo.id}")
29+
println("Peso: ${pokemonInfo.weight}")
30+
println("Altura: ${pokemonInfo.height}")
31+
println("Tipos: ${pokemonInfo.types.map { it.type.name }.joinToString(", ")}")
32+
33+
println("\nCadena de evolución:")
34+
pokemonInfo.evolutionChain.forEach { evolution ->
35+
println("- ${evolution.name}")
36+
}
37+
38+
println("\nJuegos en los que aparece:")
39+
pokemonInfo.games.forEach { game ->
40+
println("- ${game.name}")
41+
}
42+
}
43+
44+
suspend fun getPokemonInfo(name: String): PokemonInfo {
45+
val client = HttpClient()
46+
val response: HttpResponse = client.get("https://pokeapi.co/api/v2/pokemon/$name") {
47+
contentType(ContentType.Application.Json)
48+
}
49+
50+
if (response.status == HttpStatusCode.OK) {
51+
return response.body()
52+
} else {
53+
throw Exception("Error al obtener información del Pokémon: ${response.status}")
54+
}
55+
}
56+
57+
data class PokemonInfo(
58+
val name: String,
59+
val id: Int,
60+
val weight: Int,
61+
val height: Int,
62+
val types: List<PokemonType>,
63+
val evolutionChain: List<Evolution>,
64+
val games: List<Game>
65+
)
66+
67+
data class PokemonType(
68+
val type: TypeInfo
69+
)
70+
71+
data class TypeInfo(
72+
val name: String
73+
)
74+
75+
data class Evolution(
76+
val name: String
77+
)
78+
79+
data class Game(
80+
val name: String
81+
)

0 commit comments

Comments
 (0)