To convert money from one currency to another currency,  we need Currency Exchange Rate Value. Yahoo is providing an online API to get currency exchange rates. Here in below example I explained how to convert Money from one currency to other using Yahoo Finance API.

Steps to Convert Currency :

Yahoo Finance API :

Observe below GET request URL. You can see the query in q parameter. Here the Currency codes were paired. Click on below link to see output XML format.

Example :

If you want to get US dollar value in Indian rupees then you have to form below URL
String url ="*"; 
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);

// Send request
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode + "\n\n");
BufferedReader in = new BufferedReader(
       new InputStreamReader(con.getInputStream()));
String outputLine;

// reading output from Request
StringBuffer response = new StringBuffer(); 
while ((outputLine = in.readLine()) != null) {

Convert XML Response to POJO class :

// Converting XML to JSON and then JSON to POJO Classes
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
QueryPojo mp = gson.fromJson(Utility.convertXMLtoJSON(response.toString()), QueryPojo.class);

Convert Currency With Exchange Rate :

String exchangeRate = mp.getQuery().getResults().getRate().getRate();
BigDecimal amountOne = new BigDecimal(amout);
BigDecimal rate = new BigDecimal(exchangeRate);



Follow this blog by Email

Popular Posts