package com.xcong.excoin.quartz.job; import com.alibaba.fastjson.JSONObject; import com.xcong.excoin.modules.platform.dao.PlatformCnyUsdtExchangeDao; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigDecimal; import java.net.HttpURLConnection; import java.net.URL; /** * 美元-人民币汇率定时任务 * * @author wzy * @date 2020-05-28 **/ @Slf4j @Component @ConditionalOnProperty(prefix = "app", name = "other-job", havingValue = "true") public class UsdtCnyExchangePriceUpdateJob { @Resource private PlatformCnyUsdtExchangeDao cnyUsdtExchangeDao; @Scheduled(cron = "0 */5 * * * ? ") public void updateUsdtCnyExchange() { BufferedReader reader = null; String result = null; StringBuffer sbf = new StringBuffer(); // 模拟浏览器 String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36"; try { URL url = new URL("https://otc-api-hk.eiijo.cn/v1/data/config/purchase-price?coinId=2¤cyId=1&matchType=0"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(30000); connection.setConnectTimeout(30000); connection.setRequestProperty("User-agent", userAgent); connection.connect(); InputStream is = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String strRead = null; while ((strRead = reader.readLine()) != null) { sbf.append(strRead); sbf.append("\r\n"); } reader.close(); result = sbf.toString(); JSONObject jsonObject = (JSONObject) JSONObject.parse(result); String code = jsonObject.getString("code"); if ("200".equals(code)) { JSONObject jsonData = (JSONObject) jsonObject.get("data"); cnyUsdtExchangeDao.updateUsdt(BigDecimal.valueOf(jsonData.getDouble("price"))); } } catch (Exception e) { e.printStackTrace(); } } }