python调用java的webservice示例

一、java端首先我使用的是java自带的对webservice的支持包来编写的服务端和发布程序,代码如下。webservice的接口代码:

代码如下:

package com.xxx.test.ws;

import javax.jws.webmethod;import javax.jws.webservice;

/** * created with intellij idea. * user: administrator * date: 14-3-5 * time: 下午3:11 */@webservice(targetnamespace = “http://xxx.com/wsdl”)public interface calculatorws { @webmethod public int sum(int add1, int add2);

@webmethod public int multiply(int mul1, int mul2);}

接口实现代码:

代码如下:

package com.xxx.test.ws;import javax.jws.webservice;/** * created with intellij idea. * user: administrator * date: 14-3-5 * time: 下午3:12 */@webservice( portname = “calculatorport”, servicename = “calculatorservice”, targetnamespace = “http://xxx.com/wsdl”, endpointinterface = “com.xxx.test.ws.calculatorws”)public class calculator implements calculatorws { public int sum(int add1, int add2) { return add1 + add2; }

public int multiply(int mul1, int mul2) { return mul1 * mul2; }}

发布webservice代码:[code]package com.xxx.test.endpoint;import com.xxx.test.ws.calculator;import javax.xml.ws.endpoint;

/** * created with intellij idea. * user: administrator * date: 14-3-10 * time: 下午3:10 */public class calclulatorpublisher { public static void main(string[] args) { endpoint.publish(“http://localhost:8080/test/calc”, new calculator()); //endpoint.publish(“http://10.3.18.44:8080/test/calc”, new calculator()); }}[/code]运行上面的这段代码,让你的webservice跑起来,接下来就可以使用python来测试你的webservice代码了。上面的代码跑起来后,你可以直接使用浏览器访问:

代码如下:

http://localhost:8080/test/calc?wsdl

来验证是否启动成功。二、python端接下来是python的测试代码:

代码如下:

#!/usr/bin/pythonimport sudsurl = ‘http://localhost:8080/test/calc?wsdl’#url = ‘http://10.3.18.44:8080/test/calc?wsdl’client = suds.client.client(url)service = client.service

print client

sum_result = service.sum(10, 34)print sum_resultprint client.last_received()

multiply_result = service.multiply(5, 5)print multiply_resultprint client.last_received()

将上述代码保存成webservice.py文件,再修改一下可执行权限:

代码如下:

chmod +x webservice.py

输出结果如下:

代码如下:

suds ( https://fedorahosted.org/suds/ ) version: 0.3.9 (beta) build: r658-20100210

service ( calculatorservice ) tns=”http://xxx.com/wsdl” prefixes (1) ns0 = “http://xxx.com/wsdl” ports (1): (calculatorport) methods (2): multiply(xs:int arg0, xs:int arg1, ) sum(xs:int arg0, xs:int arg1, ) types (4): multiply multiplyresponse sum sumresponse

44 44 25 25

三、常见问题

注意,在执行上面的代码时,有可能提示:

代码如下:

traceback (most recent call last): file “ws.py”, line 1, in import sudsimporterror: no module named suds

说缺少依赖的包,我们可以手工下载安装suds包。

代码如下:

wget http://downloads.sourceforge.net/project/python-suds/suds/0.3.9/suds-0.3.9.tar.gz?r=http%3a%2f%2fsourceforge.net%2fprojects%2fpython-suds%2ffiles%2f&ts=1394436413&use_mirror=nchctar zxvf suds-0.3.9.tar.gzcd suds-0.3.9sudo python setup.py install

ok。

发表评论