1. Add the java.net.http module to your project's dependencies. If you're using Maven, add the following dependency to your `pom.xml`:
2. Create a component or service class where you'll handle the API requests. For example, let's create a `ApiService` class:
3. Inject the `ApiService` into your controller or wherever you need to use it. For example, in a controller:
In this example, the `ApiService` class encapsulates the logic for making the API request using `HttpClient`. The `fetchDataFromApi` method sends a GET request to the specified URL and returns the response body as a string. The `MyController` class demonstrates how you can use the `ApiService` to fetch data from the API. The `/data` endpoint invokes the `getDataFromApi` method, which calls the `fetchDataFromApi` method of the `ApiService`. If an exception occurs during the API request, the error message is returned instead. Remember to handle exceptions appropriately and add any necessary error handling or parsing logic based on the API response structure.
Post a Comment