Sunday, January 28, 2024

Rest Get Api Example

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

public class RestApiExample {

public static void main(String[] args) {

try {

// Replace this URL with the actual endpoint you want to call

String apiUrl = "https://api.example.com/data";

// Create a URL object

URL url = new URL(apiUrl);

// Open a connection to the URL

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// Set the request method to GET

connection.setRequestMethod("GET");

// Get the response code

int responseCode = connection.getResponseCode();

// Read the response from the API

if (responseCode == HttpURLConnection.HTTP_OK) {

BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String line;

StringBuilder response = new StringBuilder();

while ((line = reader.readLine()) != null) {

response.append(line);

}

reader.close();

// Print the response

System.out.println("Response: " + response.toString());

} else {

System.out.println("API call failed. Response Code: " + responseCode);

}

// Close the connection

connection.disconnect();

} catch (Exception e) {

e.printStackTrace();

}

}

}


No comments:

Post a Comment