当前位置: 代码迷 >> Web前端 >> 利用soapui跟jdk API访问webservice
  详细解决方案

利用soapui跟jdk API访问webservice

热度:148   发布时间:2012-08-31 12:55:03.0
利用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";
	
	// 调用WS
	private 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>


六、说明:获取到报文后,可用利用jdk自带的XML dom API或dom4j、jdom等API进行XML解析,获取您想要的数据。
  相关解决方案