目录

Spring WS - Writing Client

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

描述
1 按照Spring WS-Writing Server一章中的说明,在com.iowiki包下更新项目countryService。
2 在com.iowiki包下的com.iowiki.client包和MainApp.java下创建CountryServiceClient.java,如以下步骤所述。

CountryServiceClient.java

package com.iowiki.client;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import com.iowiki.GetCountryRequest;
import com.iowiki.GetCountryResponse;
public class CountryServiceClient extends WebServiceGatewaySupport {
   public GetCountryResponse getCountryDetails(String country){
      String uri = "http://localhost:8080/countryService/";
      GetCountryRequest request = new GetCountryRequest();
      request.setName(country);
      GetCountryResponse response =(GetCountryResponse) getWebServiceTemplate()
         .marshalSendAndReceive(uri, request);
      return response;
   }
}

MainApp.java

package com.iowiki;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import com.iowiki.client.CountryServiceClient;
public class MainApp {
   public static void main(String[] args) {
      CountryServiceClient client = new CountryServiceClient();
      Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
      marshaller.setContextPath("com.iowiki");
      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,并使用run as Java Application命令。 如果应用程序一切正常,它将打印以下消息。

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

在这里,我们为基于SOAP的Web服务创建了一个Client - CountryServiceClient.java 。 MainApp使用CountryServiceClient对Web服务进行命中,发出post请求并获取数据。

↑回到顶部↑
WIKI教程 @2018