import
com.google.gson.Gson;
import
com.google.gson.JsonArray;
import
com.google.gson.JsonObject;
import
java.io.BufferedReader;
import
java.io.IOException;
import
java.io.InputStreamReader;
import
java.net.HttpURLConnection;
import
java.net.URL;
import
org.springframework.stereotype.Controller;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.ResponseBody;
@Controller
public
class
CountryController {
@RequestMapping
(
"/getCountryDetailsByCapital"
)
public
@ResponseBody
JsonObject getCountryDetailsByCapital(String capital)
throws
IOException
{
JsonObject jsonObject =
new
JsonObject();
jsonObject = getDetails(capital);
JsonObject outputJsonObject =
new
JsonObject();
capital = jsonObject.get(
"capital"
).toString();
String region = jsonObject.get(
"region"
).toString();
String subRegion
= jsonObject.get(
"subregion"
).toString();
String area = jsonObject.get(
"area"
).toString();
String population
= jsonObject.get(
"population"
).toString();
outputJsonObject.addProperty(
"capital"
, capital);
outputJsonObject.addProperty(
"region"
, region);
outputJsonObject.addProperty(
"subRegion"
,
subRegion);
outputJsonObject.addProperty(
"area"
, area);
outputJsonObject.addProperty(
"population"
,
population);
return
outputJsonObject;
}
private
JsonObject getDetails(String capital)
throws
IOException
{
StringBuilder responseData =
new
StringBuilder();
JsonArray jsonArray =
null
;
URL url =
null
;
url =
new
URL(
+ capital);
JsonObject jsonObject =
null
;
HttpURLConnection con
= (HttpURLConnection)url.openConnection();
con.setRequestMethod(
"GET"
);
con.setRequestProperty(
"User-Agent"
,
"Mozilla/5.0"
);
int
responseCode = con.getResponseCode();
System.out.println(
"\nSending 'GET' request to URL : "
+ url);
try
(BufferedReader in
=
new
BufferedReader(
new
InputStreamReader(
con.getInputStream()))) {
String line;
while
((line = in.readLine()) !=
null
) {
responseData.append(line);
}
jsonArray =
new
Gson().fromJson(
responseData.toString(), JsonArray.
class
);
jsonObject = jsonArray.get(
0
).getAsJsonObject();
}
return
jsonObject;
}
}