利用soapui和jdk API访问webservice
继上一篇(http://redhacker.iteye.com/blog/1444508)关于在jdk6下如何创建webservice之后,本篇将讲述如何利用jdk API结合soapui工具编写简单webservice访问。
一、启动hello webservice服务。启动方式参见上篇博客
启动后效果如下:
二、打开soapui工具。工具下载不再赘述。
三、新建WSDL project。
四、发起ws请求,获取请求与返回报文。
五、根据请求报文编写java请求程序。
package com.je.ws.client;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;public class HelloServiceTest {public static String HELLO_WS_URL = "http://127.0.0.1:8001/HelloServicePort";// 调用WSprivate static void testHelloService(String name) throws Exception,IOException {// 构建请求报文StringBuffer sendMsgBuffer = new StringBuffer("<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:jav="http://www.javaedu.com">");sendMsgBuffer.append("<soapenv:Header/>").append("<soapenv:Body>").append("<jav:hello>").append("<arg0>").append(name).append("</arg0>").append("</jav:hello>").append("</soapenv:Body>").append("</soapenv:Envelope>");String sendMsg = sendMsgBuffer.toString();// 开启HTTP连接?URL url = new URL(HELLO_WS_URL);HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();// 设置HTTP请求相关信息httpConn.setRequestProperty("Content-Length",String.valueOf(sendMsg.getBytes().length));httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");httpConn.setRequestMethod("POST");httpConn.setDoOutput(true);httpConn.setDoInput(true);// 进行HTTP请求OutputStream outObject = httpConn.getOutputStream();outObject.write(sendMsg.getBytes());// 关闭输出流outObject.close();// 获取HTTP响应数据InputStreamReader isr = new InputStreamReader(httpConn.getInputStream(), "utf-8");BufferedReader inReader = new BufferedReader(isr);StringBuffer result = new StringBuffer();String inputLine;while ((inputLine = inReader.readLine()) != null) {result.append(inputLine);}// 打印HTTP响应数据System.out.println(result);// 关闭输入流inReader.close();isr.close();}// 测试主方法public static void main(String[] args) throws IOException, Exception {testHelloService("jack");}}
<?xml version="1.0" ?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:helloResponse xmlns:ns2="http://www.javaedu.com"><return>Hello,jack</return></ns2:helloResponse></S:Body></S:Envelope>