一个WebService
来源:互联网 发布:易辛模型Python 编辑:程序博客网 时间:2024/05/20 07:18
1、取汇率
currencyURL.properties:
AMERICAS=http://www.bloomberg.com/markets/currencies/americas_currencies.htmlASIA/PACIFIC=http://www.bloomberg.com/markets/currencies/asiapac_currencies.htmlEUROPE/AFRICA/MIDDLEEAST=http://www.bloomberg.com/markets/currencies/eurafr_currencies.htmlYAHOO=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 necessaryHttpMethodParams 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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ParserConfigurationException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 找到table的个数trNodeList 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与TargetCurrencyString[] 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;}}
。。。
0 0
- 一个WebService
- webservice的一个实例
- 一个WEBSERVICE的例子
- 创建一个WebService服务端
- 创建一个WebService项目
- 搭建一个WebService实例
- 一个简单的WebService服务
- 一个axis2 webservice helloword例子
- 一个WebService的助手类
- webservice调用一个小错误
- 一个webservice的初级例子
- gsoap写一个c++ webservice
- 一个webservice的初级例子
- 怎么样去debug一个webservice
- 一个webservice的初级例子
- 如何写一个webservice接口
- gsoap写一个c++ webservice
- 用eclipse写一个webservice
- [转]通过六个题目彻底掌握String
- 深度学习物体检测(八)——YOLO2
- GuestName处理方法
- 删除重复结点
- C++函数模板示例
- 一个WebService
- Fragment
- 反射机制的理解及其用途
- SQL注入全过程,含实例初步注入--绕过验证,直接登录安全较低公司网站登陆框如下:可以看到除了账号密码之外
- 分布式系统与集群的区别
- 关于腾讯云服务器配置tomcat和发布web项目的总结
- Callable接口和Runnable接口
- 详细了解哈夫曼树和背包问题
- B/S结构模式的发展史(有助了解)