获取实时汇率代码片段

获取实时汇率

通过yahoo 基金提供的url ,可查询实时汇率,例如

http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20("USDCNY",%20"USDHKD")&env=store://datatables.org/alltableswithkeys&format=json

查询返回json如下:

{"query":{"count":2,"created":"2014-12-31T08:22:04Z","lang":"zh-CN","results":{"rate":[{"id":"USDCNY","Name":"USD to CNY","Rate":"6.1983","Date":"12/31/2014","Time":"3:22am","Ask":"6.1992","Bid":"6.1975"},{"id":"USDHKD","Name":"USD to HKD","Rate":"7.7552","Date":"12/31/2014","Time":"3:22am","Ask":"7.7554","Bid":"7.755"}]}}}

 查询其他币种只需要改变下查询条件即可。

查询其他币种到美元的代码如下:

public RateInfo getRate(final CurrencyCodeEnum currency) throws Exception {
		
		logger.info("--通过YQL到yahoo抓取实时汇率--");
		
		final RateInfo rateInfo = new RateInfo();
		try {
			Parser parser=new Parser();
			
			StringBuffer yqlUrl = new StringBuffer("http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in (\"");
			yqlUrl.append(StringUtils.upperCase(currency.toString())).append("USD");
			yqlUrl.append("\")&env=store://datatables.org/alltableswithkeys&format=json");
			parser.setURL(yqlUrl.toString());
			parser.parse(new NodeFilter() {
				
				/** Comment for <code>serialVersionUID</code> */
				private static final long serialVersionUID = 1L;

				@Override
				public boolean accept(Node arg0) {
					JSONObject obj = (JSONObject)JSONArray.parse(arg0.toHtml());
					JSONObject query =obj.getJSONObject("query");
					JSONObject results =query.getJSONObject("results");
					Assert.notNull(results);
					JSONObject rate =	results.getJSONObject("rate");
					Assert.notNull(rate);
					rateInfo.setCurrencyName(currency.toString());
					rateInfo.setBuyRate(rate.getString("Rate"));
					SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
					try {
						rateInfo.setPubTime(format.parse(rate.getString("Date")));
					} catch (ParseException e) {
						e.printStackTrace();
					}
					return false;
				}
			});
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		logger.info("--通过YQL到yahoo抓取实时汇率,返回汇率:{}--", rateInfo);
		
		return rateInfo;
		
	}

 

 

参考http://stackoverflow.com/questions/3139879/how-do-i-get-currency-exchange-rates-via-an-api-such-as-google-finance

 

你可能感兴趣的:(实时汇率查询 汇率查询)