最近做项目,涉及到web-service调用,现学了一个星期,现简单的做一个小结。下面实现的是对传喜物流系统(http://vip.cxcod.com/podapi/getpodstr.asmx?wsdl)的订单跟踪(web-service调用)功能。
一. 使用axis1.x调用webservice方法
axis的最常用版本:1.4和2.0版本。以下为1.4版本
核心代码:
// webserviceurl
service_url = "http://vip.cxcod.com/podapi/getpodstr.asmx?wsdl";
service service = new service();
call call = (call) service.createcall();
call.settargetendpointaddress(new java.net.url(service_url));
// 设置要调用的方法
// http://intelink.net/是wsdl中definitions根节点的targetnamespace属性值
call.setoperationname(new qname("http://intelink.net/","getstrbyjobno"));
// 该方法需要的参数
call.addparameter("custno",
org.apache.axis.encoding.xmltype.xsd_string,
javax.xml.rpc.parametermode.in);
call.addparameter("passwd",
org.apache.axis.encoding.xmltype.xsd_string,
javax.xml.rpc.parametermode.in);
call.addparameter("jobno",
// 方法的返回值类型
call.setreturntype(org.apache.axis.encoding.xmltype.xsd_string);
// call.setusesoapaction(true); //call.setsoapactionuri("http://intelink.net/getstrbyjobno");
// 调用该方法, new object[] { custno, passwd, jobno}为参数列表
string xmlstr = call.invoke(new object[] { custno, passwd, jobno}).tostring();
} catch (exception e) {
e.printstacktrace();
}
java用这种方式调用webservice,需要注意的地方:
1. 服务器未能识别 http 标头 soapaction 的值:
症状一:
web service + asp.net 应用程序部署到服务器默认目录中,在ie中用http://<服务器地址>/<程序目录名>/<默认启动页面名>发生“服务器未能识别 http 标头 soapaction 的值”错误。
症状二:
在java平台上调用.net web service的服务时,出现"服务器未能识别 http 标头 soapaction 的值"。
症状三:
在java平台下调用.net web service,出现数据时有时无。
解决对策:
给.net的webservice类(即.asmx文件下的类)添加属性[soapdocumentservice(routingstyle=soapserviceroutingstyle.requestelement)]
小知识:
什么是soapaction?它在wsdl中有何作用?
soapaction http request header被用来标识soap http请求的目的地,其值是个uri地址。soap发送并不限制格式、uri特征或其必须可解析,那么在这种情况下,发送一个http soap请求时,其http客户端必须使用/指明soapaction http request header。
soapaction header的内容可以被用在服务端,诸如:防火墙适当的过滤基于http的soap请求消息等场景。soapaction header的值为空串("")表示soap消息的目的地由http请求的uri标识;无值则表示没有指定这条消息的目的地。
本人补充:
在.net环境调用.net webservice出现 “soapaction 值在 xml web services 的所有方法中不唯一的错误”,也可以通过此法解决。
2. 为了java能够调用webservice的方法,所以。netp写的webserviced的每个方法都要声明为rpc方法,即添加"[soaprpcmethod.....]".
例如:[webmethod]
[soaprpcmethod(use=soapbindinguse.literal,action= http://tempuri.org/helloworld", requestnamespace = "http://tempuri.org/", responsenamespace = "http://tempuri.org/")]
3. 对返回值、参数的处理上:
应尽量将webservice方法的返回值、参数都写成字符串(string)不要使用复杂对象类型,这样便于在网络上传输。避免了复杂对象类型的不易转换问题。。。对于返回类型是字符串数组型的,可以设置返回类型为org.apache.axis.encoding.xmltype.soap_vector或java.lang.string[].class.
二.利用xfire调用webservice
xfire是新一代的java web服务引擎,xfire使得在javaee应用中发布web服务变得轻而易举。和其他web服务引擎相比,xfire的配置非常简单,可以非常容易地和spring集成,它使得java开发人员终于可以获得和.net开发人员一样的开发效率。
核心代码:
service service = new objectservicefactory().create(iwebservice.class);
xfireproxyfactory factory =
new xfireproxyfactory(xfirefactory.newinstance().getxfire());
string url= "http://localhost:8080/webservices/services/webservices";
iwebservice iw = (iwebservice) factory.create(service, url);
list list=iw.gettest();