Apache Axis 是早期廣泛使用的 Java Web Service 框架,雖然 Axis2 已取代其地位,但在維護舊系統時仍需了解如何使用 Axis 1.x 客戶端呼叫 Axis2 部署的服務。本文透過完整代碼示範如何建立客戶端連線並呼叫遠端服務。
專案需包含以下 JAR 檔案:
package samples.clients;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
public class StockQuoteServiceClient {
public static void main(String[] args) {
try {
// 服務端點 URL,指向 Axis2 部署的 WSDL
String endpointURL = "https://localhost:8080/Axis2Web/services/StockQuoteService?wsdl";
Service service = new Service();
Call call = (Call) service.createCall();
// 設定目標端點位址
call.setTargetEndpointAddress(new java.net.URL(endpointURL));
// 設定操作名稱(需與 WSDL 定義一致)
call.setOperationName(new QName("https://quickstart.samples/xsd", "getPrice"));
// 新增輸入參數
call.addParameter("symbol", XMLType.SOAP_STRING, ParameterMode.IN);
// 設定回傳型別
call.setReturnType(XMLType.SOAP_STRING);
// 呼叫服務並取得結果
String ret = (String) call.invoke(new Object[] { "ShenBin" });
System.out.println("服務回應: " + ret);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Service.createCall() 建立 Call 實例ParameterMode.IN 表示單向輸入參數,另有 INOUT、OUT 可供選擇XMLType.SOAP_STRING 對應 Java String 型別ClassNotFoundException,請確認所有依賴 JAR 已加入 classpath官方文件參考:Apache Axis 專案首頁