
上一节讲了 axis2通过wsdl生成客户端程序并本地调用 ,这种方法由于得配置环境变量,运行dos命令,之后根据生成的代码来编写输出代码,相比较为复杂一些。这节说一下利用axis2纯手动调用网上免费webservice服务,使用这种方式较为简单一些,只需要在引入axis
上一节讲了axis2通过wsdl生成客户端程序并本地调用,这种方法由于得配置环境变量,运行dos命令,之后根据生成的代码来编写输出代码,相比较为复杂一些。这节说一下利用axis2纯手动调用网上免费webservice服务,使用这种方式较为简单一些,只需要在引入axis2包后创建一个java类就可以达到我们的目的了
项目结构如下图:
在引入axis2的jar包后,只需要新建一个testWebService2的java类就够了,下面具体看一下这个类中代码
注意:代码中.wsdl的服务地址链接一定要先在浏览器中运行一下,看是否能成功打开,成功后方可用于代码中
package com.test.weather;
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;
public class testWebService2 {
public static void main(String[] args) throws Exception {
// axis2利用网上免费webservice服务一个城市的天气情况
ServiceClient sender = new ServiceClient();
Options option = new Options();
option.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI);
option.setAction("http://WebXml.com.cn/getWeather");
EndpointReference epfs = new EndpointReference(
"http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx?wsdl");
option.setTransportInProtocol(Constants.TRANSPORT_HTTP);
option.setTo(epfs);
sender.setOptions(option);
OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace omNs = fac.createOMNamespace("http://WebXml.com.cn/", "");
OMElement data = fac.createOMElement("getWeather", omNs);
OMElement theCityCode = fac.createOMElement("theCityCode ", omNs);
OMElement theUserID = fac.createOMElement("theUserID ", omNs);
theCityCode.setText("北京");
theUserID.setText("");
data.addChild(theCityCode);
data.addChild(theUserID);
OMElement result = sender.sendReceive(data);
//System.out.println(result);
//----------------
Iterator in = result.getChildrenWithLocalName("getWeatherResult");
while(in.hasNext()){
OMElement om = (OMElement)in.next();
Iterator in2 = om.getChildElements();
while(in2.hasNext()){
System.out.println(in2.next().toString());
//System.out.println(((OMElement)in2.next()).getText());
}
}
}
}
运行代码中------以上的代码就会得到结果
有结果可以看出信息是xml格式的,如果想去掉节点,直接输出信息,需要把代码中------下方的代码去注释运行,结果如下
利用axis2纯手动调用网上免费webservice服务的介绍就完事了,较上一节的方式,两种方式各有优缺点,上一节的方式操作复杂点,这节的方式简单点,但是对网络依赖大,所以操作时,一定要在浏览器中运行一下.wsdl的服务地址链接,成功打开后方可用于自己的代码中
在研究axis2访问webservice服务的过程发现一些别的方式,但操作时报出了一些错误,下节将说一下具体的情况
