Today we will see how we can call Rest API in Liferay by using Spring RestTemplate. We just need to add dependencies related to Spring and accordingly write our client.
So lets start this step by step :-
Step 1:- Add Dependencies
Just open your build.gradle file and add two dependencies related to gradle.
build.gradle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.2.2.RELEASE' | |
compile group: 'org.springframework', name: 'spring-web', version: '5.0.3.RELEASE' | |
Step 2:- Use RestTemplte to write the client
In your java class you can use RestTemplate Class to call various APIs . Here i am using one open source rest api that will give us country details.
CountryImpl.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public JSONArray getCountryDetail(String countryName) { | |
JSONArray data = null; | |
try { | |
RestTemplate restTemplate = new RestTemplate(); | |
String baseURL = "https://restcountries.com/v3.1/name/"+countryName; | |
URI uri = UriComponentsBuilder.fromUriString(baseURL).build().toUri(); | |
ResponseEntity<String> result = restTemplate.getForEntity(uri, String.class); | |
System.out.println("Status Code : " + result.getStatusCode()); | |
data = JSONFactoryUtil.createJSONArray(result.getBody()); | |
System.out.println(data); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return data; | |
} |
Related Post:-
No comments:
Post a Comment