1. 程式人生 > >實時匯率轉換

實時匯率轉換

最近公司業務需要外匯轉換,這裡記錄下匯率實時更新的處理方式

  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