axis2 webservice Client (天气预报 )

蜀川居 2013-11-28

packageits.bgp.service;

importorg.apache.axiom.om.OMAbstractFactory;

importorg.apache.axiom.om.OMElement;

importorg.apache.axiom.om.OMFactory;

importorg.apache.axiom.om.OMNamespace;

importorg.apache.axis2.AxisFault;

importorg.apache.axis2.addressing.EndpointReference;

importorg.apache.axis2.client.Options;

importorg.apache.axis2.client.ServiceClient;

importorg.apache.axis2.transport.http.HTTPConstants;

publicclassClient{

privatestaticStringurl="http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx";

//端点引用指接口位置

privatestaticEndpointReferencetargetEpr=newEndpointReference(url);

//有抽象OM工厂获取OM工厂,创建requestSOAP包

privatestaticOMFactoryfac=OMAbstractFactory.getOMFactory();

publicstaticOMElementgetOMMethod(StringmethodStr,Stringnamespace,

Stringtns,String[]pars,String[]vals){

//创建命名空间

OMNamespacenms=fac.createOMNamespace(namespace,tns);

//创建OMElement方法元素,并指定其在nms指代的名称空间中

OMElementmethod=fac.createOMElement(methodStr,nms);

//添加方法参数名和参数值

for(inti=0;i<pars.length;i++){

//创建方法参数OMElement元素

OMElementparam=fac.createOMElement(pars[i],nms);

//设置键值对参数值

param.setText(vals[i]);

//讲方法元素添加到method方法元素中

method.addChild(param);

}

returnmethod;

}

publicstaticOptionsgetClientOptions(Stringaction){

//创建requestsoap包请求选项

Optionsoptions=newOptions();

//设置options的soapAction

options.setAction(action);

//设置requestsoap包的端点引用(接口地址)

options.setTo(targetEpr);

//如果报错提示Content-Length,请求内容长度

options.setProperty(HTTPConstants.CHUNKED,"false");//把chunk关掉后,会自动加上Content-Length。

returnoptions;

}

publicstaticOMElementgetWeather(Stringaction,StringmethodStr,

Stringnamespace,Stringtns,String[]pars,String[]vals){

OMElementresult=null;

try{

ServiceClientclient=newServiceClient();

client.setOptions(getClientOptions(action));

result=client.sendReceive(getOMMethod(methodStr,namespace,tns,

pars,vals));

}catch(AxisFaulte){

e.printStackTrace();

}

returnresult;

}

publicstaticvoidmain(String[]args){

Stringaction="http://WebXml.com.cn/getWeatherbyCityName";

StringmethodStr="getWeatherbyCityName";

Stringnamespace="http://WebXml.com.cn/";

Stringtns="xsd";

String[]pars={"theCityName"};

String[]vals={"北京"};

OMElementresult=null;

result=getWeather(action,methodStr,namespace,tns,pars,vals);

System.out.println(result);

}

}

相关推荐