📅  最后修改于: 2023-12-03 14:51:31.898000             🧑  作者: Mango
本文介绍了使用Java编写的在线汇率API。该API允许程序员轻松地获取实时的汇率数据,并且提供了丰富的功能和灵活的定制选项。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public class ExchangeRateAPI {
public static void main(String[] args) {
try {
String baseCurrency = "USD";
String targetCurrency = "EUR";
// 替换为你选择的汇率API提供商的URL
String apiUrl = "https://api.example.com/rates?base=" + baseCurrency + "&target=" + targetCurrency;
// 发送 HTTP GET 请求
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
// 处理响应
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 解析响应JSON
JSONObject json = new JSONObject(response.toString());
double exchangeRate = json.getDouble("rate");
// 输出汇率
System.out.println("汇率: " + exchangeRate);
} else {
// 处理错误情况
System.out.println("获取汇率失败. 响应代码: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
请注意,示例仅演示了如何发送请求并解析响应数据。在实际应用中,你可能还需要处理错误情况、设置请求头、处理身份验证等其他内容。具体的操作取决于所选的汇率API提供商的要求和文档。