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

Posted 阿若蜜意

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了调用百度汇率api 获取各国的汇率值相关的知识,希望对你有一定的参考价值。

设置一个定时任务,每天更新汇率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" initial-delay="3000" ref="flightService" method="queryIndexFlight"  />
        <task:scheduled ref="systemService" method="clearSmsCache" cron="0 30 23 ? * * " />  
        <task:scheduled ref="exhiMainService" method="handleCuXiaoEnd" cron="0 0 8 * * ?" />
        <task:scheduled ref="exhiMainService" method="outDateExhi" cron="0 30 0 ? * * " />
        <task:scheduled ref="xuQiuService" method="setXuQiuCount" cron="* * 10,12,14,15,16,17 * * ? " />
        <task:scheduled ref="columnService" method="cleanOutDateExhi" cron="0 30 0 ? * * " />
        <task:scheduled ref="orderMainService" method="kaiZhanTiShi" cron="0 0 7 * * ?" />
        <task:scheduled ref="yuDengJiPushService" method="queryYuDengJiPush" cron="0 30 8 * * ?"/>
        <task:scheduled ref="searchRecordService" method="batchSave" cron="0 0/10 * * * ? "/>
        <task:scheduled ref="fenXiaoRecordService" method="batchSave" cron="0 10 0 * * ? "/>
        <task:scheduled ref="logService" method="batchSave" cron="0 0/2 * * * ? "/>
        <task:scheduled ref="systemService" method="kaiFaRenYuanPush" cron="0 0 9 * * ?"/>
        <!-- <task:scheduled ref="huiLvService" method="queryHuiLv" cron="0 0 21 * * ?"/> -->
         <!-- <task:scheduled ref="huiLvService" method="queryHuiLv" cron="0 0/1 * * * ?"/> -->
    </task:scheduled-tasks>  
</beans>

spring-tasks.xml 配置在spring-context.xml里面

<?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:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" 
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"
    default-lazy-init="true">

    <description>Spring Configuration</description>
    <!-- 加载配置属性文件 -->
    <context:property-placeholder ignore-unresolvable="true" location="classpath:jeesite.properties" />
    
     <task:scheduled-tasks scheduler="scheduler">  
        <task:scheduled ref="orderMainService" method="cuiKuan" cron="${allipay.cron.cuikuan}" />  
    </task:scheduled-tasks>  
    <!-- 加载应用属性实例,可通过  @Value("#{APP_PROP[‘jdbc.driver‘]}") String jdbcDriver 方式引用 -->
    <util:properties id="APP_PROP" location="classpath:jeesite.properties" local-override="true"/>
    
    <!-- 使用Annotation自动注册Bean,解决事物失效问题:在主容器中不扫描@Controller注解,在SpringMvc中只扫描@Controller注解。  -->
    <context:component-scan base-package="com.thinkgem.jeesite,com.allinpay"><!-- base-package 如果多个,用“,”分隔 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
     <!-- MyBatis begin -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.thinkgem.jeesite"/>
        <property name="typeAliasesSuperType" value="com.thinkgem.jeesite.common.persistence.BaseEntity"/>
        <property name="mapperLocations" value="classpath:/mappings/**/*.xml"/>
        <property name="configLocation" value="classpath:/mybatis-config.xml"></property>
    </bean>
    
    <!-- 扫描basePackage下所有以@MyBatisDao注解的接口 -->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <property name="basePackage" value="com.thinkgem.jeesite"/>
        <property name="annotationClass" value="com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao"/>
    </bean>
    
    <!-- 定义事务 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    
    <!-- 配置 Annotation 驱动,扫描@Transactional注解的类定义事务  -->
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
    <!-- MyBatis end -->
    
    <!-- 配置 JSR303 Bean Validator 定义 -->
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

    <!-- 缓存配置 -->
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:${ehcache.configFile}" />
    </bean>
    
    <!-- 计划任务配置,用 @Service @Lazy(false)标注类,用@Scheduled(cron = "0 0 2 * * ?")标注方法 -->
    <task:executor id="executor" pool-size="10"/> <task:scheduler id="scheduler" pool-size="10"/>
    <task:annotation-driven scheduler="scheduler" executor="executor" proxy-target-class="true"/>
    
    <!-- 数据源配置, 使用 BoneCP 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> 
        <!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->
        <property name="driverClassName" value="${jdbc.driver}" />
        
        <!-- 基本属性 url、user、password -->
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        
        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="${jdbc.pool.init}" />
        <property name="minIdle" value="${jdbc.pool.minIdle}" /> 
        <property name="maxActive" value="${jdbc.pool.maxActive}" />
        
        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="60000" />
        
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />
        
        <property name="validationQuery" value="${jdbc.testSql}" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        
        <!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用)
        <property name="poolPreparedStatements" value="true" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> -->
        
        <!-- 配置监控统计拦截的filters -->
        <property name="filters" value="stat" /> 
    </bean>
    
    <!-- 数据源配置, 使用应用服务器的数据库连接池 
    <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/jeesite" />-->

    <!-- 数据源配置, 不使用连接池 
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>-->
    <bean id="startupListener" class="com.thinkgem.jeesite.modules.sys.listener.StartupListener"/>
    <bean id="Scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" /> 
    <import resource="spring-tasks.xml"/>
</beans>

spring-context.xml 配置在web.xml 里面

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">

    <display-name>wanxiuAdmin</display-name>

    <!-- Context ConfigLocation -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:/spring-context*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>com.thinkgem.jeesite.modules.sys.listener.WebContextListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>  
    </listener>
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- Apache Shiro -->
    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetFilterLifecycle</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- PageCache, cache .html suffix.
    <filter>
        <filter-name>PageCacheFilter</filter-name>
        <filter-class>com.thinkgem.jeesite.common.filter.PageCachingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>PageCacheFilter</filter-name>
        <url-pattern>/</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>PageCacheFilter</filter-name>
        <url-pattern>*.html</url-pattern>
    </filter-mapping>-->

    <!-- SiteMesh -->
    <filter>
        <filter-name>sitemeshFilter</filter-name>
        <filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>sitemeshFilter</filter-name>
        <url-pattern>/a/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>sitemeshFilter</filter-name>
        <url-pattern>/f/*</url-pattern>
    </filter-mapping>
    
    <!-- MVC Servlet -->
    <servlet>
        <servlet-name>springServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:/spring-mvc*.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- Activiti -->
    <servlet>
        <servlet-name>RestletServlet</servlet-name>
        <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class>
        <init-param>
            <param-name>org.restlet.application</param-name>
            <param-value>com.thinkgem.jeesite.modules.act.rest.ActRestApplication</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>RestletServlet</servlet-name>
        <url-pattern>/act/rest/service/*</url-pattern>
    </servlet-mapping>

    <!-- DruidStatView -->
    <servlet>
        <servlet-name以上是关于调用百度汇率api 获取各国的汇率值的主要内容,如果未能解决你的问题,请参考以下文章

GDAX api - 获取返回不一致结果的历史汇率

多线程获取官方汇率

多线程获取官方汇率

phpweb 怎么调用其它网站的足球比分、外汇汇率等模块

使用奇怪的 JSON 文件格式查找汇率键值

前端如何获取实时美元汇率