7.4.6 创建客户端调用程序
客户端通过URLConnection来调用Service提供的服务。客户端的运行程序主要包括3个步骤。
建立URLConnection连接;
发送SOAP请求消息;
接收返回SOAP消息。
运行客户端程序,需要以下面的request.xml作为输入参数,它是一个SOAP/HTTP的消息格式,具体内容如下:
<?xml version="1.0" encoding="UTF-8"?> <env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" > <env:Body> <getHello xmlns="hello"> <in0 xmlns="hello">Aihu</in0> </getHello> </env:Body> </env:Envelope> |
例程7-3显示了客户端的调用程序。
例程7-3 HttpClient.java
import java.io.*; import java.NET.URL; import java.NET.URLConnection; public class HttpClient { public static void main(String[] args) throws Exception {
//创建URLConnection的连接 URLConnection connection = new URL("http://localhost:8192/hello/").openConnection(); connection.setDoOutput(true); OutputStream os = connection.getOutputStream(); //发送请求消息 FileInputStream fis = new FileInputStream("request.xml"); int c; while ((c = fis.read()) >= 0) { os.write(c); } os.close(); fis.close(); //读取返回消息 BufferedReader in = new BufferedReader(new InputStreamReader (connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } } |
在ServiceMix的服务启动后,直接运行Ant命令执行上面的客户端调用程序。将输出下面的结果:
<?xml version='1.0' encoding='UTF-8'?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Body> <getHelloout xmlns="hello">Hello Aihu! This is SERVICEMIX Web Service Response. </getHelloout> </soapenv:Body> </soapenv:Envelope>
|
【责任编辑:
夏书 TEL:(010)68476606】