首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

JAX-RPC 實作 Web 服務(二):開發 Client 端呼叫 RPC 服務

     編輯:Java 相關知識

Client 端環境設定

須將 Axis 相關 JAR 加入 Client 端 Classpath(勿放入 JRE ext 目錄):

  • axis.jar、jaxrpc.jar、commons-logging-1.0.4.jar、commons-discovery-0.2.jar、saaj.jar、wsdl4j-1.5.1.jar
  • 可選:activation.jar、mail.jar(若服務端使用)

建議在 ~/.profile 或 IDE 專案設定中配置 CLASSPATH。

撰寫 Client 程式

import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceException;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import java.net.URL;

public class BookSearcherClient {
  private static final String ENDPOINT = "https://localhost:8080/axis/BookSearcher.jws";
  private Service service;
  private Call call;
  private URL endpointUrl;

  public Object[] search(String keyword) throws Exception {
    if (service == null) service = new Service();
    if (call == null) call = (Call) service.createCall();
    if (endpointUrl == null) endpointUrl = new URL(ENDPOINT);

    call.setTargetEndpointAddress(endpointUrl);
    call.setOperationName(new QName("https://soapinterop.org/", "search"));

    // 呼叫遠端方法,參數以 Object[] 傳遞
    Object[] results = (Object[]) call.invoke(new Object[] { keyword });
    return results;
  }

  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.err.println("Usage: java BookSearcherClient [keyword]");
      return;
    }
    BookSearcherClient client = new BookSearcherClient();
    Object[] books = client.search(args[0]);
    System.out.println("Returned books for keyword '" + args[0] + "':");
    for (Object b : books) System.out.println("  " + b);
  }
}

關鍵步驟解析

  1. Service/Call:JAX-RPC 標準介面,Axis 提供實作。Service 為 Factory 產生 Call。
  2. Endpoint 設定:setTargetEndpointAddress() 指定 .jws URL。
  3. Operation 名稱:用 QName 表達 SOAP 操作,命名空間固定 https://soapinterop.org/,本地名為方法名 search。
  4. invoke():將參數封裝為 Object[],同步阻塞呼叫,回傳結果亦為 Object[](SOAP 不保留泛型資訊)。

執行驗證

$ java BookSearcherClient design
Returned books for keyword 'design':
  Emotional Design
  Indexed

結果與伺服器端直接測試一致,證明 RPC 呼叫成功。

總結與遷移建議

  • JAX-RPC 以「介面與實作分離」設計,Client 僅依賴標準 API,若改用其他 RPC 實作(如 CXF)只需換 JAR 與建立 Call 方式。
  • JAX-RPC 已由 JAX-WS (JSR-224) 取代,新專案建議直接使用 JAX-WS 或 Spring Web Services;維護舊系統時本文流程仍適用。
  • 實務上常搭配 wsimport 由 WSDL 產生 Stub,避免手寫 QName 與 invoke 細節。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved