- Spring 5.0 Projects
- Nilang Patel
- 186字
- 2021-07-02 12:34:57
Designing the client for World Bank API
We need to fetch the GDP data from WorldBank API. As we discussed, it is REST end point, where we have to send few parameters and will get the response. For this, we will use RestTemplate to make REST call. The following is the definition for the com.packt.external.WorldBankApiClient class, which is used to invoke the World Bank API and process its response to return List<CountryGDP>:
@Service
public class WorldBankApiClient {
String GDP_URL = "http://api.worldbank.org/countries/%s/indicators/NY.GDP.MKTP.CD?"
+ "format=json&date=2008:2018";
public List<CountryGDP> getGDP(String countryCode) throws ParseException {
RestTemplate worldBankRestTmplt = new RestTemplate();
ResponseEntity<String> response
= worldBankRestTmplt.getForEntity(String.format(GDP_URL, countryCode), String.class);
//the second element is the actual data and its an array of object
JSONParser parser = new JSONParser();
JSONArray responseData = (JSONArray) parser.parse(response.getBody());
JSONArray countryDataArr = (JSONArray) responseData.get(1);
List<CountryGDP> data = new ArrayList<CountryGDP>();
JSONObject countryDataYearWise=null;
for (int index=0; index < countryDataArr.size(); index++) {
countryDataYearWise = (JSONObject) countryDataArr.get(index);
String valueStr = "0";
if(countryDataYearWise.get("value") !=null) {
valueStr = countryDataYearWise.get("value").toString();
}
String yearStr = countryDataYearWise.get("date").toString();
CountryGDP gdp = new CountryGDP();
gdp.setValue(valueStr != null ? Double.valueOf(valueStr) : null);
gdp.setYear(Short.valueOf(yearStr));
data.add(gdp);
}
return data;
}
}
推薦閱讀
- Application Development with Qt Creator(Second Edition)
- 網絡協議工程
- C++黑客編程揭秘與防范
- MERN Quick Start Guide
- 物聯網之魂:物聯網協議與物聯網操作系統
- 企業私有云建設指南
- SSL VPN : Understanding, evaluating and planning secure, web/based remote access
- Mastering TypeScript 3
- 新手易學:新手學淘寶開店
- 搶占下一個智能風口:移動物聯網
- 人人都該都懂的互聯網思維
- Practical Web Penetration Testing
- Selenium WebDriver 3 Practical Guide
- Building RESTful Web Services with .NET Core
- 互聯網戰略變革與未來