- 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;
}
}
推薦閱讀
- Modern JavaScript Web Development Cookbook
- 物聯(lián)網(wǎng)(IoT)基礎(chǔ):網(wǎng)絡(luò)技術(shù)+協(xié)議+用例
- GPS/GNSS原理與應(yīng)用(第3版)
- 物聯(lián)網(wǎng)之魂:物聯(lián)網(wǎng)協(xié)議與物聯(lián)網(wǎng)操作系統(tǒng)
- 互聯(lián)網(wǎng)基礎(chǔ)資源技術(shù)與應(yīng)用發(fā)展態(tài)勢(2021—2023)
- SSL VPN : Understanding, evaluating and planning secure, web/based remote access
- Mastering JavaFX 10
- 通信十年:擁抱互聯(lián)網(wǎng)
- 網(wǎng)絡(luò)利他行為研究:積極心理學(xué)的視角
- 網(wǎng)絡(luò)綜合布線(第2版)
- 5G技術(shù)核心與增強(qiáng):從R15到R17
- 云計(jì)算技術(shù)與標(biāo)準(zhǔn)化
- Selenium WebDriver 3 Practical Guide
- 物聯(lián)網(wǎng)M2M開發(fā)技術(shù):基于無線CPU-Q26XX
- Oracle ADF Faces Cookbook