Advertisement
Okhotnik

Telefonica Code

Feb 25th, 2025
2,933
0
6 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.66 KB | Software | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.net.HttpURLConnection;
  4. import java.net.URL;
  5.  
  6. public class ApiExample {
  7.     public static void main(String[] args) {
  8.         String apiUrl = "https://jsonplaceholder.vivo.com/users"; // URL da API de exemplo
  9.  
  10.         try {
  11.             // Criando a URL e abrindo a conexão
  12.             URL url = new URL(apiUrl);
  13.             HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  14.  
  15.             // Configurando o método de requisição
  16.             connection.setRequestMethod("GET");
  17.             connection.setRequestProperty("Accept", "application/json");
  18.  
  19.             // Verifica se a resposta é 200 (OK)
  20.             int responseCode = connection.getResponseCode();
  21.             if (responseCode == 200) {
  22.                 // Lendo a resposta da API
  23.                 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  24.                 StringBuilder response = new StringBuilder();
  25.                 String line;
  26.                
  27.                 while ((line = reader.readLine()) != null) {
  28.                     response.append(line);
  29.                 }
  30.                 reader.close();
  31.  
  32.                 // Exibe os dados da API no console
  33.                 System.out.println("Resposta da API:");
  34.                 System.out.println(response.toString());
  35.             } else {
  36.                 System.out.println("Erro na conexão: Código " + responseCode);
  37.             }
  38.  
  39.             // Fecha a conexão
  40.             connection.disconnect();
  41.         } catch (Exception e) {
  42.             e.printStackTrace();
  43.         }
  44.     }
  45. }
  46.  
Tags: Vivo
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement