WebService(WEB服务)--获取网络数据

运用WebService(WEB服务),可以很方便快捷的获取想要的数据。[url]http://www.webxml.com.cn/zh_cn/index.aspx[/url]网站提供了很多web服务。下面以获取汇率为例,来说明webservice的用法。
这个例子运用到了dom4j操作xml文件,先是从两个web服务中分别获取数据,最后根据具体需求将数据整合在一起,生成一个xml文件。本例中需要用到的webservice有两个:[url]http://webservice.webxml.com.cn/WebServices/ExchangeRateWebService.asmx[/url]与[url]http://webservice.webxml.com.cn/WebServices/ForexRmbRateWebService.asmx[/url]。完整版代码见附件,精简版代码如下,哈哈
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
* getExchangeRate
*/

/**
* getForexRmbRate
*/

/**
* 调用webservice得到汇率服务
* @author gerry
* 2010-09-06
*/
public class ExchangeRateXML{
private static String encodeOut = "GBK";
private static String encodeIn = "UTF-8";

private static Proxy proxy;//代理
private static String proxyStr = "10.3.1.93";//代理IP地址 若不用代理请设置proxyStr="";
private static int proxyCode = 3128;//代理端口

private static int COUNT = 10;//尝试连接次数

/**
* 单例模式
*/
private static ExchangeRateXML exchangeRateXML;

/**
* 私有的构造方法
*/
private ExchangeRateXML(){

}

/**
* public的获取单例对象的方法
*/
public static ExchangeRateXML getInstance(){
if(exchangeRateXML==null){
exchangeRateXML = new ExchangeRateXML();
InetSocketAddress isa = new InetSocketAddress(proxyStr, proxyCode);
proxy = new Proxy(Proxy.Type.HTTP, isa);
}
return exchangeRateXML;
}


/**
* 通过dom4j生成xml文件
* @return 成功true 失败false
*/
private boolean createExchangeRateXMLFile(String fileName){
boolean flag = false;
Document document=null;
SAXReader reader = new SAXReader();

Map map = new HashMap();
map.put("xxx", "");
reader.getDocumentFactory().setXPathNamespaceURIs(map);

try{
InputStream is = getSoapInputStream(1);//得到输入流
document=reader.read(is);//将输入流转化为document
List list = document.selectNodes("//xxx:ExchangeRate");
Element relativeRootElement = list.get(0).getParent().getParent();//diffgr:diffgram节点 相对根节点
DecimalFormat df = new DecimalFormat("###0.0000"); //保留小数点后4位
Element e = null;
for(int i=0; i<=6; i++){
e = list.get(i);
//先把名称改为"美元Currency"的格式
e.element("Currency").setText("美元"+e.element("Currency").getText());
e.element("Code").setText("USD-"+e.element("Code").getText());
}

is = getSoapInputStream(2);//得到输入流
Document doc = reader.read(is); //将输入流转化为document
List l = doc.selectNodes("//xxx:ForexRmbRate");
Element ele = null;
for (Iterator it = l.iterator(); it.hasNext();) {
ele = it.next();
//ele.element("Name").setText(ele.element("Name").getText()+"人民币");
ele.element("Name").setText(ele.element("Symbol").getText()); //为了解决在Linux上中文字符的问题
ele.element("Symbol").setText(ele.element("Symbol").getText()+"-RMB");
}
Element element = (Element)doc.selectSingleNode("//xxx:getForexRmbRate");
Element elementCopy = element.createCopy();//copy节点
relativeRootElement.add(elementCopy);
//或relativeRootElement.appendContent(element.getParent());

OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(encodeOut);
format.setIndent(" ");
XMLWriter writer = new XMLWriter(new FileWriter(new File(fileName)),format);
writer.write(document);
writer.close();
flag = true;
}catch (Exception e){
e.printStackTrace();
}
return flag;
}


/**
* 从xml文件中获取数据 采用XPath
* @return
*/
@SuppressWarnings("unchecked")
private static void getExchangeRateDataFromXMLFile(String fileName){
SAXReader reader = new SAXReader();
Map map = new HashMap();
map.put("aaa", "");
reader.getDocumentFactory().setXPathNamespaceURIs(map);
try {
InputStream is = new FileInputStream(fileName);
Document document = reader.read(is);
//上行代码也可以写成Document document = reader.read(new File(fileName));
//找到ForexRmbRate节点
List list = document.selectNodes("//aaa:ForexRmbRate");
for (Iterator it = list.iterator(); it.hasNext();) {
Element elm = it.next();
String temp = null;
temp = elm.element("BasePrice").getText();
temp = elm.element("fBuyPrice").getText();
temp = elm.element("SellPrice").getText();
}

} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}


/**
* 用户把SOAP请求发送给服务器端,并返回服务器点返回的输入流
* flag : 为1时代表getExchangeRate,为2时代表getForexRmbRate
* @return 服务器端返回的输入流,供客户端读取
*/
private InputStream getSoapInputStream(int flag) throws Exception {
//InputStreamReader isr = null;
try {
String soap = getSoapRequest(flag);
if (soap == null) {
return null;
}
String urlStr = null;
String SOAPActionValue = null;
if(flag==1){
urlStr = "http://webservice.webxml.com.cn/WebServices/ExchangeRateWebService.asmx";
SOAPActionValue = "http://webxml.com.cn/getExchangeRate";
}else if(flag==2){
urlStr = "http://webservice.webxml.com.cn/WebServices/ForexRmbRateWebService.asmx";
SOAPActionValue = "http://webxml.com.cn/getForexRmbRate";
}
URL url = new URL(urlStr);
URLConnection conn = null;
if (!proxyStr.equals("")) {
conn = url.openConnection(proxy);
} else {
conn = url.openConnection();
}
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Length", Integer.toString(soap.length()));
conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
conn.setRequestProperty("SOAPAction",SOAPActionValue);
OutputStream ops = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(ops, encodeIn);
osw.write(soap);
osw.flush();
osw.close();
InputStream is = conn.getInputStream();
// isr = new InputStreamReader(is, encodeIn);
// return isr;
return is;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}


/**
* 获取soap请求头
* flag : 为1时代表getExchangeRate,为2时代表getForexRmbRate
* @return 用户将要发送给服务器的soap请求
*/
private String getSoapRequest(int flag) {
StringBuilder sb = new StringBuilder();
if(flag==1){
sb.append(""
+ " + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
+ "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
+ " "
+ "" + "A"
+ "
"
+ "
");
}else if(flag==2){
sb.append(""
+ " + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
+ "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
+ " "
+ "
"
+ "
");
}
return sb.toString();
}


/**
* 外部可访问的方法,获得汇率数据
*/
public void getExchangeRate(){
for(int i=0; i if(ExchangeRateXML.getInstance().createExchangeRateXMLFile("ExRate.xml")){
break;
}
}
getExchangeRateDataFromXMLFile("ExRate.xml");
}
}

这个链接中有一个简单的webservice例子,是获取天气预报的:[url]http://qinshuwei.com/webservic.html[/url]

你可能感兴趣的:(XML)