Kubernate

Microservice # Call Rest EndPoint (RestTemplate)

 Option 1: Using HttpURLConnection (pure Java SE, no extra dependency)

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 {

            // REST API endpoint

            URL url = new URL("https://jsonplaceholder.typicode.com/posts/1");

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

 

            // Set request method

            conn.setRequestMethod("GET");

            conn.setRequestProperty("Accept", "application/json");

 

            // Check response code

            if (conn.getResponseCode() != 200) {

                throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());

            }

 

            // Read response

            BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

            String output;

            System.out.println("Response from API .... \n");

            while ((output = br.readLine()) != null) {

                System.out.println(output);

            }

 

            conn.disconnect();

 

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}


Option 2: Using Spring’s RestTemplate (simpler if you’re in Spring Boot)

Add dependency in pom.xml (already included in Spring Boot starter):

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-web</artifactId>

</dependency>

Code:

import org.springframework.web.client.RestTemplate;

 

public class RestApiSpringExample {

    public static void main(String[] args) {

        RestTemplate restTemplate = new RestTemplate();

 

        String url = "https://jsonplaceholder.typicode.com/posts/1";

 

        // GET request

        String response = restTemplate.getForObject(url, String.class);

 

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

    }

}


🔑 Key Points

  • HttpURLConnection → works in plain Java 8, no external libraries.
  • RestTemplate → much easier if you’re already using Spring Boot.
  • For POST requests, you can use conn.setDoOutput(true) with HttpURLConnection or restTemplate.postForObject() in Spring.

👉 Since you’re already working with Spring Boot + microservices, I’d recommend RestTemplate (or even WebClient if you move to Spring WebFlux).

Would you like me to extend this with a POST request example (sending JSON payload to the API)? That’s often the next step when integrating microservices.

 


No comments:

Post a Comment

Spring Boot - Bean LifeCycle

 Here is a clear, step-by-step lifecycle of a Spring Boot application , explained in a simple + interview-ready way. 🔄 Spring Boot Applica...

Kubernate