获取实时汇率的接口 Java
时间: 2023-12-09 20:07:01 浏览: 60
你可以使用以下的Java代码获取实时的汇率信息:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class CurrencyConverter {
public static void main(String[] args) {
String fromCurrency = "USD";
String toCurrency = "EUR";
double amount = 100;
double exchangeRate = getExchangeRate(fromCurrency, toCurrency);
double convertedAmount = exchangeRate * amount;
System.out.println(amount + " " + fromCurrency + " = " + convertedAmount + " " + toCurrency);
}
public static double getExchangeRate(String fromCurrency, String toCurrency) {
String url = "https://api.exchangerate-api.com/v4/latest/" + fromCurrency;
try {
URL urlObj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String jsonResponse = response.toString();
double exchangeRate = Double.parseDouble(jsonResponse.split("\"" + toCurrency + "\":")[1].split(",")[0]);
return exchangeRate;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
```
上述的代码使用了 https://exchangerate-api.com 提供的 API 来获取实时汇率信息。你需要将上述的代码中的 `fromCurrency` 和 `toCurrency` 更改为你所需的货币代码,并将 `amount` 更改为你所需的金额。你也可以使用其他的实时汇率 API 来获取汇率信息,只需要将上述代码中的 `url` 更改为对应的 API 地址即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)