实时汇率转换

最近公司业务需要外汇转换,这里记录下汇率实时更新的处理方式

  1. 申请汇率API接口(这里用的是聚合数据的API,免费每天调用100次)
  2. 编程用到的语言(网站上有对应的基本测试代码)
  3. 新建测试项目,导入所需jar包(Myeclipse)
  4. 根据需求更改代码
  5. 调用成功(大功告成)
    代码贴出来:
 package com.goldatg.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * 
 * @项目名称:@{project_name}
 * @类名称:@{type_name}
 * @类描述:
 * @创建人:{user}
 * @创建时间:2017-5-24下午4:02:35
 * 
 * @修改人:
 * @修改时间:2017-5-24下午4:02:35
 * @修改备注:
 * @version:
 */
public class ExchangeUtil {
    public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static String userAgent =  "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";

    //配置您申请的KEY
    public static final String APPKEY ="*****************";

    //1.常用汇率查询
    public static void getRequestExchange(){
        String result =null;
        String url ="http://op.juhe.cn/onebox/exchange/query";//请求接口地址
        Map params = new HashMap();//请求参数
            params.put("key",APPKEY);//应用APPKEY(应用详细页查询)

        try {
            result =net(url, params, "GET");
            JSONObject object = JSONObject.fromObject(result);
            if(object.getInt("error_code")==0){
                System.out.println(object.get("result"));
            }else{
                System.out.println(object.get("error_code")+":"+object.get("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //2.货币列表
    public static String getRequestCurrencyList(){
        String result =null;
        String url ="http://op.juhe.cn/onebox/exchange/list";//请求接口地址
        String currencyList = null;//货币列表
        Map params = new HashMap();//请求参数
            params.put("key",APPKEY);//应用APPKEY(应用详细页查询)

        try {
            result =net(url, params, "GET");
            JSONObject object = JSONObject.fromObject(result);
            if(object.getInt("error_code")==0){
                System.out.println(object.get("result"));
                currencyList = object.get("result").toString();
            }else{
                System.out.println(object.get("error_code")+":"+object.get("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return currencyList;
    }

    //3.实时汇率查询换算
    public static String getRequestConversion(String currency){
        String result =null;
        String url ="http://op.juhe.cn/onebox/exchange/currency";//请求接口地址
        String multiple = null;//转换后得到的倍数
        Map params = new HashMap();//请求参数
            params.put("from","USD");//转换汇率前的货币代码
            params.put("to",currency);//转换汇率成的货币代码
            params.put("key",APPKEY);//应用APPKEY(应用详细页查询)

        try {
            result =net(url, params, "GET");
            JSONObject object = JSONObject.fromObject(result);//得到当前返回的结果
            String str = object.get("result").toString();//根据键“result”得到值
            JSONArray objArray = JSONArray.fromObject(str);//转换成JSON数组对象
            multiple = (String) objArray.getJSONObject(0).get("result");//得到精确值
            if(object.getInt("error_code")==0){
                System.out.println(object.get("result"));
                System.out.println(multiple);
            }else{
                System.out.println(object.get("error_code")+":"+object.get("reason"));

            }
        } catch (Exception e) {
            e.printStackTrace(); 
        }
        return multiple;
    }



    public static void main(String[] args) {

    }

    /**
     *
     * @param strUrl 请求地址
     * @param params 请求参数
     * @param method 请求方法
     * @return  网络请求字符串
     * @throws Exception
     */
    public static String net(String strUrl, Map params,String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if(method==null || method.equals("GET")){
                strUrl = strUrl+"?"+urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if(method==null || method.equals("GET")){
                conn.setRequestMethod("GET");
            }else{
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params!= null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                        out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }

    //将map型转为请求参数型
    public static String urlencode(Map<String,Object>data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

这里要注意的是:这里针对的是web项目,如要测试请新建一个Servlet在浏览器进行访问,控制台输出,得到的结果是JSONObject对象,根据不同的需求,进行分解转化java对象;
JSONObject所需6个jar包,如有需要点击这里可以免费下载http://download.csdn.net/detail/qq_33624284/9851046

猜你喜欢

转载自blog.csdn.net/qq_33624284/article/details/72677531