axis2 調用 .net 的 webservice,按照下面的步驟,一步一步來。
- 下載
axis2(到apache官網(wǎng)下載)。 - 我下載的是
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開發(fā)目錄下。 - 建一個測試類
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 需要傳遞的參數(shù),可以通過對這個對象賦值操作完成,如上面,我要查廣州的天氣,就設置為 city.setTheCityName("廣州");
注意,關鍵的地方:
由于 .net webservice 中返回的是 ArrayOfString,java 中沒有這個對象,所以 axis2 會自動生成這個對象,然后轉換成對應的數(shù)組即可,如:
String[] str = array.getString();