axis2
调用 .net
的 webservice
,按照下面的步骤,一步一步来。
- 下载
axis2
(到apache官网下载)。 - 我下载的是
axis2-1.7.7-bin.zip
,解压到当前文件夹。 - 进入bin目录(
D:\changhrData\javalib\axis2-1.7.7-bin\axis2-1.7.7\bin
)。 - 打开
cmd
,进入第3步的bin目录,输入
wsdl2java.bat -uri http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl
回车。
- 之后会在
bin
目录下生成一个src
目录,将src
目录下的两个类拷贝到eclipse开发目录下。 - 建一个测试类
Test.java
,代码如下 :
import cn.com.webxml.WeatherWebServiceStub;
import cn.com.webxml.WeatherWebServiceStub.ArrayOfString;
import cn.com.webxml.WeatherWebServiceStub.GetWeatherbyCityName;
public class Test {
public static void test1(){
try{
WeatherWebServiceStub stub = new WeatherWebServiceStub();
stub._getServiceClient().getOptions().setProperty(
org.apache.axis2.transport.http.HTTPConstants.CHUNKED,
Boolean.FALSE);
GetWeatherbyCityName city = new GetWeatherbyCityName();
city.setTheCityName("广州");
ArrayOfString array = stub.getWeatherbyCityName(city).getGetWeatherbyCityNameResult();
String[] str = array.getString();
for(String s : str){
System.out.println(s);
}
}catch(Exception e){
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) throws Exception{
test1();
}
}
需要注意的是这个类GetWeatherbyCityName
,这个本来是.net webservice
中的一个方法,如下 :
POST /WebServices/WeatherWebService.asmx HTTP/1.1
Host: www.webxml.com.cn
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://WebXml.com.cn/getWeatherbyCityName"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<getWeatherbyCityName xmlns="http://WebXml.com.cn/">
<theCityName>string</theCityName>
</getWeatherbyCityName>
</soap:Body>
</soap:Envelope>
用 axis2
生成 java
代码后,会自动生成一个对应的对象,webservice
需要传递的参数,可以通过对这个对象赋值操作完成,如上面,我要查广州的天气,就设置为 city.setTheCityName("广州")
;
注意,关键的地方:
由于 .net webservice
中返回的是 ArrayOfString
,java
中没有这个对象,所以 axis2
会自动生成这个对象,然后转换成对应的数组即可,如:
String[] str = array.getString();