Java使用SOAP方式调用Web service

工作上用到的调用webservice的方式,使用Java底层的方式,不需要第三方jar包

目前是基本款满足了工作的需求了,里面还没有使用到soapheader验证,下回找个实例再写一个吧……

package com.zhl.common;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPEnvelope;
//import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;
import org.w3c.dom.Document;
import com.sun.xml.internal.ws.client.BindingProviderProperties;
import com.sun.xml.internal.ws.developer.JAXWSProperties;

public class WebServiceClient {
	String nameSpace = "";
	String wsdlUrl = "";
	String serviceName = "";
	String portName = "";
	String responseName = "";
	String elementName = "";
	int timeout = 20000;

	/**
	 * 
	 * @param nameSpace
	 * @param wsdlUrl
	 * @param serviceName
	 * @param portName
	 * @param elementName
	 * @param responseName
	 */

	public WebServiceClient(String nameSpace, String wsdlUrl,
			String serviceName, String portName, String element,
			String responseName) {
		this.nameSpace = nameSpace;
		this.wsdlUrl = wsdlUrl;
		this.serviceName = serviceName;
		this.portName = portName;
		this.elementName = element;
		this.responseName = responseName;
	}

	/**
	 * 
	 * @param nameSpace
	 * @param wsdlUrl
	 * @param serviceName
	 * @param portName
	 * @param elementName
	 * @param requestName
	 * @param responseName
	 * @param timeOut
	 *            毫秒
	 */

	public WebServiceClient(String nameSpace, String wsdlUrl,
			String serviceName, String portName, String element,
			String responseName, int timeOut) {
		this.nameSpace = nameSpace;
		this.wsdlUrl = wsdlUrl;
		this.serviceName = serviceName;
		this.portName = portName;
		this.elementName = element;
		this.responseName = responseName;
		this.timeout = timeOut;
	}

	public String sendMessage(HashMap<String, String> inMsg) throws Exception {
		// 创建URL对象
		URL url = null;
		try {
			url = new URL(wsdlUrl);
		} catch (Exception e) {
			e.printStackTrace();
			return "创建URL对象异常";
		}
		// 创建服务(Service)
		QName sname = new QName(nameSpace, serviceName);
		Service service = Service.create(url, sname);

		// 创建Dispatch对象
		Dispatch<SOAPMessage> dispatch = null;
		try {
			dispatch = service.createDispatch(new QName(nameSpace, portName),
					SOAPMessage.class, Service.Mode.MESSAGE);
		} catch (Exception e) {
			e.printStackTrace();
			return "创建Dispatch对象异常";
		}

		// 创建SOAPMessage
		try {
			SOAPMessage msg = MessageFactory.newInstance(
					SOAPConstants.SOAP_1_2_PROTOCOL).createMessage();
			msg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");

			SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();

			// 创建SOAPHeader(不是必需)
			// SOAPHeader header = envelope.getHeader();
			// if (header == null)
			// header = envelope.addHeader();
			// QName hname = new QName(nameSpace, "username", "nn");
			// header.addHeaderElement(hname).setValue("huoyangege");

			// 创建SOAPBody
			SOAPBody body = envelope.getBody();
			QName ename = new QName(nameSpace, elementName, "q0");
			SOAPBodyElement ele = body.addBodyElement(ename);
			// 增加Body元素和值
			for (Map.Entry<String, String> entry : inMsg.entrySet()) {
				ele.addChildElement(new QName(nameSpace, entry.getKey()))
						.setValue(entry.getValue());
			}

			// 超时设置
			dispatch.getRequestContext().put(
					BindingProviderProperties.CONNECT_TIMEOUT, timeout);
			dispatch.getRequestContext().put(JAXWSProperties.REQUEST_TIMEOUT,
					timeout);

			// 通过Dispatch传递消息,会返回响应消息
			SOAPMessage response = dispatch.invoke(msg);

			// 响应消息处理,将响应的消息转换为doc对象
			Document doc = response.getSOAPPart().getEnvelope().getBody()
					.extractContentAsDocument();
			String ret = doc.getElementsByTagName(responseName).item(0)
					.getTextContent();
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}
}

调用例子,这个webservice的服务端是别人的,我仅仅只是做示例用

package com.zhl.common;

import java.util.HashMap;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// 该WebService文档==>http://ws.webxml.com.cn/webservices/DomesticAirline.asmx
		WebServiceClient ws = new WebServiceClient("http://WebXml.com.cn/",
				"http://ws.webxml.com.cn/webservices/DomesticAirline.asmx",
				"DomesticAirline", "DomesticAirlineSoap12",
				"getDomesticAirlinesTime", "getDomesticAirlinesTimeResult");
		HashMap<String, String> inMsg = new HashMap<String, String>();
		inMsg.put("startCity", "宁波");
		inMsg.put("lastCity", "青岛");
		inMsg.put("theDate", "2017-05-11");

		try {
			String ret = ws.sendMessage(inMsg);
			System.out.println(ret.toString()); // 没有对结果做处理
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}



  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值