Selier 2013-04-24
package service.cilent; import java.util.Iterator; import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.soap.SOAP11Constants; import org.apache.axis2.Constants; import org.apache.axis2.addressing.EndpointReference; import org.apache.axis2.client.Options; import org.apache.axis2.client.ServiceClient; import org.apache.axis2.transport.http.HttpTransportProperties.ProxyProperties; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; public class JavaServicesClient { private static EndpointReference targetEPR = new EndpointReference("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx"); @SuppressWarnings("unchecked") public void getResult() throws Exception { ServiceClient sender = new ServiceClient(); sender.setOptions(buildOptions()); //得到axis2定义的xml文件格式 OMElement result = sender.sendReceive(buildParam()); //将axis2的xml格式转换为dom的为XML格式 Document doc = DocumentHelper.parseText(result.toString()); //获取根节点 Element rootElt = doc.getRootElement(); // 获取根节点下的getWeatherbyCityNameResult子节点 Iterator iter = rootElt.elementIterator("getWeatherbyCityNameResult"); while(iter.hasNext()){ Element recordEle = (Element) iter.next(); // 获取子节点getWeatherbyCityNameResult下的子节点string Iterator iters = recordEle.elementIterator("string"); while(iters.hasNext()){ Element itemEle = (Element) iters.next(); //输出string的值 System.out.println(itemEle.getTextTrim()); } } } private static OMElement buildParam() { OMFactory fac = OMAbstractFactory.getOMFactory(); OMNamespace omNs = fac.createOMNamespace("http://WebXml.com.cn/", ""); OMElement data = fac.createOMElement("getWeatherbyCityName", omNs); OMElement inner = fac.createOMElement("theCityName", omNs); inner.setText("深圳"); data.addChild(inner); return data; } private static Options buildOptions() { Options options = new Options(); options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI); options.setAction("http://WebXml.com.cn/getWeatherbyCityName"); options.setTo(targetEPR); // options.setProperty 如果不是通过代理上网,此句可省 // options.setProperty(HTTPConstants.PROXY, buildProxy()); options.setTransportInProtocol(Constants.TRANSPORT_HTTP); return options; } /** * 本机采用代理服务器上网时,需要设置代理 * * @return */ public static ProxyProperties buildProxy() { ProxyProperties proxyProperties = new ProxyProperties(); proxyProperties.setProxyName("代理名称"); proxyProperties.setProxyPort(8080); return proxyProperties; } public static void main(String[] args) throws Exception { JavaServicesClient s = new JavaServicesClient(); s.getResult(); } }