Is there some currency converter library that enables to convert a value from a specific currency to another? Or should I implement my how class for this?
If someone has some kind of example it would be great...
Ideally you should not write your own formulas to convert the currency due to the dynamic nature of currencies. It will be a good idea to access some public APIs, which can be reliably used to do the currency conversion. One of such API is Yahoo currency convertor API. Yahoo API is very simple. The basic general request for getting the current currency rate between two currencies looks like:
http://download.finance.yahoo.com/d/quotes.csv?s=[From Currency][To Currency]=X&f=l1&e=.cs
For example, in order to get the current currency rate between US Dollars and Israeli Shekels, the following request should be constructed:
http://download.finance.yahoo.com/d/quotes.csv?s=USDILS=X&f=l1&e=.cs
Getting the currency rate information is pretty straight forward. It starts with a basic interface to define a general converter behavior:
public interface CurrencyConverter {
public float convert(String currencyFrom, String currencyTo) throws Exception;
}
And the implementing class with a basic main application showing its usage:
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.IOException;
public class YahooCurrencyConverter implements CurrencyConverter
{
public float getConversionRate(String from, String to) throws IOException
{
HttpClientBuilder builder = HttpClientBuilder.create();
try (CloseableHttpClient httpclient = builder.build())
{
HttpGet httpGet = new HttpGet("http://quote.yahoo.com/d/quotes.csv?s=" + from + to + "=X&f=l1&e=.csv");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpGet, responseHandler);
return Float.parseFloat(responseBody);
}
}
public static void main(String[] arguments) throws IOException
{
YahooCurrencyConverter yahooCurrencyConverter = new YahooCurrencyConverter();
float current = yahooCurrencyConverter.getConversionRate("USD", "ILS");
System.out.println(current);
}
}
IMPORTANT: Yahoo or any other provider is not obliged to provide such APIs unless you are not paying them. So you may need to look for some paid APIs in case you are building a commercial applications depending on them. Or you need to be vigil to be sure that free APIs are UP and RUNNING properly for you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With