理想情况下,由于货币的动态特性,您不应编写自己的公式来转换货币.访问一些可以可靠地用于进行货币转换的公共API是个好主意.其中一个API是Yahoo货币转换器API.Yahoo API非常简单.获得两种货币之间当前货币汇率的基本一般要求如下:
http://download.finance.yahoo.com/d/quotes.csv?s=[From Currency] [货币] = X&f = l1&e = .cs
例如,为了获得美元和以色列谢克尔之间的当前货币汇率,应构建以下请求:
http://download.finance.yahoo.com/d/quotes.csv?s=USDILS=X&f=l1&e=.cs
获取货币汇率信息非常简单.它从一个基本接口开始,用于定义一般的转换器行为:
public interface CurrencyConverter {
public float convert(String currencyFrom, String currencyTo) throws Exception;
}
Run Code Online (Sandbox Code Playgroud)
并且实现类具有显示其用法的基本主应用程序:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
重要提示:除非您不支付,否则雅虎或任何其他提供商没有义务提供此类API.因此,您可能需要查找一些付费API,以防您根据它们构建商业应用程序.或者您需要保持警惕,以确保免费的API正常运行并正常运行