Created
July 26, 2019 22:08
-
-
Save vacax/75197d177169c892a068133e0ea23bfb to your computer and use it in GitHub Desktop.
Consulta y creación de Estudiante en Cliente Rest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package edu.pucmm.hlr; | |
import kong.unirest.HttpResponse; | |
import kong.unirest.JsonNode; | |
import kong.unirest.Unirest; | |
import org.json.JSONObject; | |
public class Main { | |
public static void main(String[] args) { | |
System.out.println("Hola Mundo Rest Cliente :-D"); | |
leerEstudiantes(); | |
// Creación de Estudiante. | |
crearEstudiante(); | |
} | |
private static void crearEstudiante() { | |
JSONObject miEstudiante = new JSONObject(); | |
miEstudiante.put("matricula", 20011136); | |
miEstudiante.put("nombre", "Samuel"); | |
miEstudiante.put("correo", "asdasd@asdasd.com"); | |
miEstudiante.put("carrera", "ISC"); | |
// | |
HttpResponse<JsonNode> response = Unirest.post("http://localhost:4567/rest/estudiantes/") | |
.header("accept", "application/json") | |
.body(miEstudiante) | |
.asJson(); | |
// | |
System.out.println("Codigo de respuesta: "+response.getStatus()); | |
if(response.getStatus() != 200){ | |
System.out.println("Error procesando"); | |
return; | |
} | |
System.out.println("Estudiante creado: "+response.getBody().toString()); | |
} | |
private static void leerEstudiantes() { | |
HttpResponse<JsonNode> response = Unirest.get("http://localhost:4567/rest/estudiantes/") | |
.header("accept", "application/json") | |
.queryString("apiKey", "123") | |
.asJson(); | |
// | |
System.out.println("Codigo respuesta del HTTP: "+response.getStatus()); | |
if(response.getStatus() != 200){ | |
System.out.println("Se presentó un error en la llamada"); | |
return; | |
} | |
JsonNode json = response.getBody(); | |
System.out.println("Es un arreglo? "+json.isArray()); | |
int cantidadElementos = json.getArray().length(); | |
System.out.println("La cantidad de elementos: "+cantidadElementos); | |
for(int i=0;i<cantidadElementos;i++){ | |
//recuperando la referencia del objeto. | |
JSONObject jsonObject = json.getArray().getJSONObject(i); | |
//presentando la información. | |
System.out.println(String.format("Estudiante[%d]-> { matricula: %d, nombre: %s }", | |
i, | |
jsonObject.getInt("matricula"), | |
jsonObject.getString("nombre"))); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment