调用百度汇率api 获取各国的汇率值

通过配置定时任务,每天更新汇率信息。代码中包含spring-tasks.xml的配置,该配置位于spring-context.xml中,而spring-context.xml在web.xml内。参考链接:https://www.cnblogs.com/SHMILYHP/p/5534408.html
摘要由CSDN通过智能技术生成

设置一个定时任务,每天更新汇率java代码如下

package com.thinkgem.jeesite.modules.huiLvApi.service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.List;

import org.activiti.engine.impl.util.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.thinkgem.jeesite.common.utils.GsonUtils;
import com.thinkgem.jeesite.modules.huiLvApi.entity.RetData;
import com.thinkgem.jeesite.modules.huiLvApi.entity.Root;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.service.DictService;

/**
 * 调用百度汇率api
 * 
 * @author Administrator
 * 
 */
@Service
@Scope
public class HuiLvService {

    @Autowired
    DictService dictService;

    /**
     * @param urlAll
     *            :请求接口
     * @param httpArg
     *            :参数
     * @return 返回结果
     */
    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            // 填入apikey到HTTP header
            connection.setRequestProperty("apikey", "0d263364faa016e5f06075b69b799087");
            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();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 定时任务每天执行调用百度汇率api
     * 
     * @throws JSONException
     */
    public void queryHuiLv() {
        String httpUrl = "http://apis.baidu.com/apistore/currencyservice/currency";
        String httpArg = null;
        Dict dict = new Dict();
        dict.setType("hui_lv");
        List<Dict> dictList = dictService.findList(dict);// 查询出数据库表中所有的汇率
        if (dictList != null && dictList.size() > 0) {
            for (Dict dt : dictList) {
                String value = dt.getValue();
                httpArg = "fromCurrency=" + value + "&toCurrency=CNY&amount=1";
                if (!"1".equals(value)) {
   // 表里面目前有个舍客勒 键值是1,所以调用百度接口时无法识别
                    String data = request(httpUrl, httpArg);
                    try {
                        if (data != null && !"".equals(data)) {
                            Root rt = GsonUtils.json2T(data, Root.class);
                            RetData retData = rt.getRetData();
                            dt.setValue(retData.getFromCurrency());// 汇率简称
                            dt.setLabel(retData.getCurrency());//
                            dt.setUpdateDate(new Date());
                            dictService.updateHuiLv(dt);
                            System.out.println(data);
                            System.out.println(retData);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 测试用
     * 
     * @param httpUrl
     * @param httpArg
     * @return
     */
    public static String newRequest(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            // 填入apikey到HTTP header
            connection.setRequestProperty("apikey", "0d263364faa016e5f06075b69b799087");
            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();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        String httpUrl = "http://apis.baidu.com/apistore/currencyservice/currency";
        String httpArg = "fromCurrency=USD&toCurrency=CNY&amount=1";
        String jsonResult = newRequest(httpUrl, httpArg);
        System.out.println(jsonResult);
    }
}

定时任务配置配置文件名称是spring-tasks.xml  (spring-tasks.xml 里面有配置如何定时执行queryHuiLv)请留意看

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:c="http://www.springframework.org/schema/c" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <!-- 定时清除手机短信redis缓存 -->
    <task:scheduled-tasks scheduler="scheduler">  
        <!-- <task:scheduled ref="yuDengJiPushService" method="queryYuDengJiPush" cron="0 0/1 * * * ?"/> --> 
        
        <task:scheduled fixed-delay="3600000"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值