- 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;
}
}
推薦閱讀
- 6G潛在關鍵技術(下冊)
- SEO 20日
- 物聯(lián)網(wǎng)檢驗檢測技術
- 無人機通信
- React:Cross-Platform Application Development with React Native
- Mastering Dart
- Microsoft Dynamics CRM 2011 Applications(MB2-868) Certification Guide
- 4G小基站系統(tǒng)原理、組網(wǎng)及應用
- jQuery Mobile Web Development Essentials
- 計算機網(wǎng)絡技術及應用
- 物聯(lián)網(wǎng)工程導論(第3版)
- 從實踐中學習手機抓包與數(shù)據(jù)分析
- 深入理解Nginx:模塊開發(fā)與架構解析
- 世界互聯(lián)網(wǎng)發(fā)展報告2021
- 小型局域網(wǎng)組建