Spring WS - 编写客户端
在本章中,我们将学习如何为 Spring WS 中创建的 Web 应用程序服务器创建客户端-使用 Spring WS编写服务器。
| 步 | 描述 |
|---|---|
| 1 | 更新 com.tutorialspoint 包下的项目countryService,如 Spring WS – 编写服务器一章中所述。 |
| 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 = "http://localhost:8080/countryService/";
GetCountryRequest request = new GetCountryRequest();
request.setName(country);
GetCountryResponse response =(GetCountryResponse) getWebServiceTemplate()
.marshalSendAndReceive(uri, request);
return response;
}
}
主应用程序.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());
}
}
启动网络服务
启动Tomcat服务器并确保我们可以使用标准浏览器访问webapps文件夹中的其他网页。
测试 Web 服务客户端
在 Eclipse 下右键单击应用程序中的 MainApp.java 并使用run as Java Application命令。如果应用程序一切正常,它将打印以下消息。
Country : United States Capital : Washington Population : 46704314 Currency : USD
在这里,我们为基于 SOAP 的 Web 服务创建了一个客户端 – CountryServiceClient.java 。MainApp 使用 CountryServiceClient 访问 Web 服务,发出 POST 请求并获取数据。