-
-
Save parzibyte/88e79d6ee511253479e68e1e3a6d1957 to your computer and use it in GitHub Desktop.
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
import java.io.BufferedReader; | |
import java.io.InputStreamReader; | |
import java.net.HttpURLConnection; | |
import java.net.URL; | |
class Main { | |
public static void main(String[] args) { | |
String url = "https://jsonplaceholder.typicode.com/todos/1"; | |
String respuesta = ""; | |
try { | |
respuesta = peticionHttpGet(url); | |
System.out.println("La respuesta es:\n" + respuesta); | |
} catch (Exception e) { | |
// Manejar excepción | |
e.printStackTrace(); | |
} | |
} | |
public static String peticionHttpGet(String urlParaVisitar) throws Exception { | |
// Esto es lo que vamos a devolver | |
StringBuilder resultado = new StringBuilder(); | |
// Crear un objeto de tipo URL | |
URL url = new URL(urlParaVisitar); | |
// Abrir la conexión e indicar que será de tipo GET | |
HttpURLConnection conexion = (HttpURLConnection) url.openConnection(); | |
conexion.setRequestMethod("GET"); | |
// Búferes para leer | |
BufferedReader rd = new BufferedReader(new InputStreamReader(conexion.getInputStream())); | |
String linea; | |
// Mientras el BufferedReader se pueda leer, agregar contenido a resultado | |
while ((linea = rd.readLine()) != null) { | |
resultado.append(linea); | |
} | |
// Cerrar el BufferedReader | |
rd.close(); | |
// Regresar resultado, pero como cadena, no como StringBuilder | |
return resultado.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment