Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created February 11, 2019 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/88e79d6ee511253479e68e1e3a6d1957 to your computer and use it in GitHub Desktop.
Save parzibyte/88e79d6ee511253479e68e1e3a6d1957 to your computer and use it in GitHub Desktop.
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