In this blog, I am covering consuming an external OData service (Northwind) from a CAP Java application using SAP BTP destination service.
Destinations: contain the connection details for the remote communication of an application.
Pre-requisites:
- Trial account on BTP
- Java application built using SAP Cloud Application Programming Model (CAP) deployed to SAP Business Technology Platform.
Create a Destination on BTP cockpit:
- Go to BTP subaccount -> space in which app is deployed -> instances -> create
- Once the service instance is created, click on instance name -> select destinations -> new destination
- Go to Referencing apps -> Click on bind instance -> select name of deployed application -> save
Consuming the destination in java code:
- Add/make sure this dependency is added you your pom.xml
- We have already configured the connection information with destination northwind_api. SAP Cloud SDK provides DestinationAccessor to retrieve destination info.
@RequestMapping(value = "/getProducts")
public String getProducts() {
String DESTINATION_NAME = "northwind_api";
try {
HttpDestination destination =
DestinationAccessor.getDestination(DESTINATION_NAME).asHttp();
HttpClient client = HttpClientAccessor.getHttpClient(destination);
HttpResponse httpResponse = null;
try {
httpResponse = client.execute(new HttpGet());
if (httpResponse.getStatusLine().getStatusCode() == 200) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(httpResponse.getEntity().getContent()));
StringBuilder result = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
return result.toString();
}
} catch (IOException e) {
return "IOException: " + e.getMessage();
}
} catch (DestinationNotFoundException | DestinationAccessException e) {
return e.getMessage();
}
return null;
}
- Got the response as below on hitting “/getProducts” endpoint
Closing:
This blog should give you a clear idea on how to consume destinations in SAP Cloud Platform Cloud Foundry environment from java code using DestinationAccessor class provided by SAP cloud SDK.
Subscribe
Login
Please login to comment
0 Comments