/**
* 根据币种获取对应对欧元的汇率
*
* @param currencyCode
* @return
*/
private BigDecimal getOtherCurrencyRateToEUR(String currencyCode) {
// 先从redis中取,如果redis中不存在从接口中拉取的数据为xml格式转成json并存入redis,过期时间10小时拉取一次
// 拉取接口:https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
//从获取的json中读取对应的比率并返回
try {
Object currencyObject = RedisUtil.get(RedisConstUtil.OFFER_GET_OTHER_CURRENCY_RATE_TO_EUR);
if (currencyObject == null || "".equals(currencyObject)) {
//拉取
String httpsurl = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
String content = HttpUtils.httpGetString(httpsurl);
JSONObject result = XmlToJsonUtil.StringXmlToJSONString(content);
List<Map<String, Object>> list = JSON.parseObject(result.getJSONObject("Cube").getJSONObject("Cube").getString("Cube"), List.class);
Map<String, Object> params = new HashMap<>();
for (Map<String, Object> item : list) {
params.put(item.get("@currency").toString(), item.get("@rate"));
}
//10小时 60*60*10 = 36000
RedisUtil.setByTime(RedisConstUtil.OFFER_GET_OTHER_CURRENCY_RATE_TO_EUR, JSONObject.toJSONString(params), 36000);
return new BigDecimal(params.get(currencyCode).toString());
} else {
Map<String, BigDecimal> currencyMap = JSON.parseObject(currencyObject.toString(), Map.class);
return currencyMap.get(currencyCode);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
//请求数据
public static String httpGetString(String url) throws Exception {
URL serverUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("pragma", "no-cache");
conn.setRequestProperty("cache-control", "no-cache");
conn.setRequestProperty("upgrade-insecure-requests", "1");
conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
conn.setRequestProperty("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
conn.setRequestProperty("accept-language", "zh-CN,zh;q=0.9");
//必须设置false,否则会自动redirect到重定向后的地址
conn.setInstanceFollowRedirects(false);
conn.connect();
String result = getReturn(conn);
return result;
}
/**
* xml字符串转json
* @param content
* @return
*/
public static JSONObject StringXmlToJSONString(String content) {
XMLSerializer xmlSerializer = new XMLSerializer();
String resultStr = xmlSerializer.read(content).toString();
JSONObject result = JSON.parseObject(resultStr);
return result;
}
需要导入
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>fakepath</groupId>
<artifactId>xom</artifactId>
<version>1.2.6</version>
</dependency>
xom.jar地址 https://download.csdn.net/download/sinat_23301457/9682275