Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.URL;
- public class ApiExample {
- public static void main(String[] args) {
- String apiUrl = "https://jsonplaceholder.vivo.com/users"; // URL da API de exemplo
- try {
- // Criando a URL e abrindo a conexão
- URL url = new URL(apiUrl);
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- // Configurando o método de requisição
- connection.setRequestMethod("GET");
- connection.setRequestProperty("Accept", "application/json");
- // Verifica se a resposta é 200 (OK)
- int responseCode = connection.getResponseCode();
- if (responseCode == 200) {
- // Lendo a resposta da API
- BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
- StringBuilder response = new StringBuilder();
- String line;
- while ((line = reader.readLine()) != null) {
- response.append(line);
- }
- reader.close();
- // Exibe os dados da API no console
- System.out.println("Resposta da API:");
- System.out.println(response.toString());
- } else {
- System.out.println("Erro na conexão: Código " + responseCode);
- }
- // Fecha a conexão
- connection.disconnect();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement