Spring WS - 编写客户端



本章中,我们将学习如何使用 Spring WS 为 Spring WS - 编写服务器 中创建的 Web 应用程序服务器创建客户端。

步骤 说明
1 按照 Spring WS 编写服务器章节所述,更新包 com.tutorialspoint 下的国家服务器项目。
2 按照以下步骤,在包 com.tutorialspoint.client 下创建 CountryServiceClient.java,在包 com.tutorialspoint 下创建 MainApp.java。

CountryServiceClient.java

package com.tutorialspoint.client;

import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import com.tutorialspoint.GetCountryRequest;
import com.tutorialspoint.GetCountryResponse;

public class CountryServiceClient extends WebServiceGatewaySupport {
   public GetCountryResponse getCountryDetails(String country){
      String uri = "https://:8080/countryService/";
      GetCountryRequest request = new GetCountryRequest();
      request.setName(country);

      GetCountryResponse response =(GetCountryResponse) getWebServiceTemplate()
         .marshalSendAndReceive(uri, request);
      return response;
   }
}

MainApp.java

package com.tutorialspoint;

import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import com.tutorialspoint.client.CountryServiceClient;

public class MainApp {
   public static void main(String[] args) {
      CountryServiceClient client = new CountryServiceClient();
      Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
      marshaller.setContextPath("com.tutorialspoint");
      client.setMarshaller(marshaller);
      client.setUnmarshaller(marshaller);
      GetCountryResponse response = client.getCountryDetails("United States");

      System.out.println("Country : " + response.getCountry().getName());
      System.out.println("Capital : " + response.getCountry().getCapital());
      System.out.println("Population : " + response.getCountry().getPopulation());
      System.out.println("Currency : " + response.getCountry().getCurrency());
   }
}

启动 Web 服务

启动 Tomcat 服务器,并确保可以使用标准浏览器从 webapps 文件夹访问其他网页。

测试 Web 服务客户端

在 Eclipse 中右键单击应用程序中的 MainApp.java,并使用 以 Java 应用程序运行 命令。如果一切正常,它将打印以下消息。

Country : United States
Capital : Washington
Population : 46704314
Currency : USD

在此,我们为基于 SOAP 的 Web 服务创建了一个客户端 – CountryServiceClient.java。MainApp 使用 CountryServiceClient 向 Web 服务提交请求,发出 post 请求并获取数据。

广告
© . All rights reserved.