使用 JDK 內置 javax.xml.rpc (JAX-RPC) 動態調用遠程 WebService,無需生成 Stub 代碼。
import javax.xml.rpc.Call;
import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceException;
import java.io.*;
import java.util.Properties;
public class WsClient {
public static void main(String[] args) throws Exception {
// 1. 讀取配置
Properties prop = new Properties();
try (InputStream in = WsClient.class.getClassLoader().getResourceAsStream("datasource.properties")) {
prop.load(in);
}
String endpoint = prop.getProperty("url", "none");
// 2. 創建動態調用
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress(endpoint);
call.setOperationName("getRefInfo"); // 遠程方法名
// 3. 調用並獲取結果
String cardInNo = "123456";
String jsonResult = (String) call.invoke(new Object[]{cardInNo});
System.out.println("返回結果:" + jsonResult);
}
}
url=https://localhost:8090/bid/services/HelloWorld
Service.createCall() 創建動態調用對象。setTargetEndpointAddress 指定 WSDL 服務地址(實際為端點 URL)。setOperationName 對應 WSDL 中的 operation 名稱。invoke(Object[]) 參數順序必須與 WSDL 定義一致。JAX-RPC 已在 Java EE 6 中標記為過時,Java 9+ 模塊化移除,新項目請勿使用。