一个WebService

1、取汇率

currencyURL.properties:

AMERICAS=http://www.bloomberg.com/markets/currencies/americas_currencies.html
ASIA/PACIFIC=http://www.bloomberg.com/markets/currencies/asiapac_currencies.html
EUROPE/AFRICA/MIDDLEEAST=http://www.bloomberg.com/markets/currencies/eurafr_currencies.html
YAHOO=http://hk.finance.yahoo.com/currency/convert?amt=1&from=USD&to=

 

代码入口:

GetInternetData getInternetData = new GetInternetData();
		try {
			currencyMaps = getInternetData.getRequestInfo();
		} catch (Exception e) {
			log.error(e.getMessage());
			//return mapping.findForward("fail");
		}

 GetInternetData.java:

 

 

读取配置文件:

/**
	 * 从网站读取数据
	 * @return
	 * @throws Exception
	 */
	public final List<Exchangerate> getRequestInfo() throws Exception {
		//读取配置文件,取得网站路径
		ResourceBundle bundle = ResourceBundle.getBundle("currencyURL");
		Enumeration<String> enums = bundle.getKeys();
		List<Exchangerate> currencyMaps = new ArrayList<Exchangerate>();
		while (enums.hasMoreElements()) {
			String key = enums.nextElement();
			//从网站中取得标签
			if(!key.equals("YAHOO")){
				log.info("==========>"+key);
				String res = getHttpRequestInfo(bundle.getString(key));
				List<Exchangerate> currencyList = getData(res,key);
				currencyMaps.addAll(currencyList);
			}
		}
		return currencyMaps;
	}

 

由URL得到Response:

private final String getHttpRequestInfo(String uri) throws Exception {
	String response = null;
	// Create an instance of HttpClient.
	HttpClient client = new HttpClient();
	// Create a method instance.
	GetMethod method = new GetMethod(uri);

	// Provide custom retry handler is necessary
	HttpMethodParams httpMethodParams = method.getParams();
	httpMethodParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
	
	try {
		int statusCode = client.executeMethod(method);

		if (statusCode != HttpStatus.SC_OK)
			throw new RuntimeException("Httpclient Method failed: "
					+ method.getStatusLine());

		response = method.getResponseBodyAsString();

		String s1 = "<table";
		String e1 = "</table>";
		int stratIndex = response.indexOf(s1);
		int endIndex = response.indexOf(e1, stratIndex) + e1.length();
		String currency = response.substring(stratIndex, endIndex);
		
		return currency;
	} finally {
		method.releaseConnection();
	}
}

 

 

组装数据:

private List<Exchangerate> getData(String response,String urlKey) throws TransformerException{
	List<Exchangerate> currencyMaps = new ArrayList<Exchangerate>();
	
	Document doc = null;
	try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(response)));
	} catch (SAXException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (ParserConfigurationException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	// 找到table的个数tr
	NodeList trNodes =doc.getDocumentElement().getElementsByTagName("tr");
	log.info(trNodes.getLength());
	for(int i=0;i<trNodes.getLength();i++){
		Node node = trNodes.item(i);
		Node theadNode = XPathAPI.selectSingleNode(node, "thead");
		if(null==theadNode){
			NodeList tdNodes = XPathAPI.selectNodeList(node, "td");
			Node tdnode = tdNodes.item(0);
			System.out.println("tdnodes: " + tdnode);
			if(null != tdnode) {
				//if ("CURRENCY".equalsIgnoreCase(tdNodes.item(0).getTextContent().trim())) continue;
				Exchangerate currency = new Exchangerate();
				//将CURRENCY截取为BaseCurrency与TargetCurrency
				String[] cs = tdNodes.item(0).getTextContent().trim().split("[-]");
				currency.setBasecurrency(cs[0]);
				currency.setSellcurrency(cs[1]);
				String amountStr = tdNodes.item(1).getTextContent().trim();
				amountStr = amountStr.replaceAll(",", "");
				currency.setWebExrate(Double.parseDouble(amountStr));
				currency.setArea(urlKey);
				//currency.setUpdatedate(date);
				currencyMaps.add(currency);
			}
		}
	}
	return currencyMaps;
}

 

。。。

 

 

 

 

方式二:

 

package tags;

import java.io.BufferedReader;

public class MainTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {		
		String fromCurrency = "HKD";
		String toCurrency = "AUD";
		String googleCur = getGoogleCurrency(fromCurrency, toCurrency);
		String yahooCur = getYahooCurrency(fromCurrency, toCurrency);
		System.out.println(googleCur+"\n"+yahooCur);
	}

	static String getGoogleCurrency(String fromCurrency, String toCurrency){
		String rtn = "";
		String strGoogleURL = "http://www.google.com/ig/calculator?hl=en&q=1" + fromCurrency + "%3D%3F" + toCurrency;
		
		try {
		    // Create a URL for the desired page
		    URL url = new URL(strGoogleURL);

		    // Read all the text returned by the server
		    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
		    String str;
		    while ((str = in.readLine()) != null) {
		    	rtn += str;
		        // str is one line of text; readLine() strips the newline character(s)
		    }
		    in.close();
		} catch (MalformedURLException e) {
		} catch (IOException e) {
		}
		return rtn;			
	}
	static String getYahooCurrency(String fromCurrency, String toCurrency){
		String rtn = "";
		String strYahooURL = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=" + fromCurrency + toCurrency + "=X";
		
		try {
		    // Create a URL for the desired page
		    URL url = new URL(strYahooURL);

		    // Read all the text returned by the server
		    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
		    String str;
		    while ((str = in.readLine()) != null) {
		    	rtn += str;
		        // str is one line of text; readLine() strips the newline character(s)
		    }
		    in.close();
		} catch (MalformedURLException e) {
		} catch (IOException e) {
		}
		return rtn;
	}
}

 

 

。。。

 

 

 

 

 

 

你可能感兴趣的:(webservice)