java客户端操作SOAP消息

时间:2021-08-13 08:33:37
package org.example.myservice;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;

import org.junit.Test;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class JunitTest {

	private String ns = "http://www.example.org/MyService/";
	private String wsdlUrl = "http://10.10.9.208:8088/ms?wsdl";
	
	@Test
	public void testMessage(){
		//1,创建消息工厂
		try {
			MessageFactory factory=MessageFactory.newInstance();
			//2,根据消息工厂创建SOAPMessage
			
			SOAPMessage messge=factory.createMessage();
			//3,创建SOAPPart
			SOAPPart part=messge.getSOAPPart() ;
			//4,获取信封
			SOAPEnvelope envelop=part.getEnvelope() ;
			//5,获取消息主题部分
			SOAPBody body=envelop.getBody();
			
			//6,创建信息
			QName qname=new QName(wsdlUrl,"add","ns");
			SOAPElement ele=body.addBodyElement(qname);
			ele.addChildElement("number1").setValue("1");
			ele.addChildElement("number2").setValue("2");
			
			messge.writeTo(System.out);
		} catch (SOAPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//测试将消息发送到服务器端
	@Test
	public void testSendMessge(){
//		1,创建服务
		
		try {
			URL url=new URL(wsdlUrl);
			QName qname=new QName(ns,"MyServiceImplService");
			Service service=Service.create(url,qname);
			
//			2,创建Dispicathc
			
			Dispatch<SOAPMessage> dispatch=service.createDispatch(new QName(ns,"MyServiceImplPort"),
					SOAPMessage.class, Service.Mode.MESSAGE);
//			3,创建消息
			SOAPMessage message=MessageFactory.newInstance().createMessage();
			SOAPBody body =message.getSOAPPart().getEnvelope().getBody();
			SOAPElement ele=body.addChildElement(new QName(ns,"add","nn"));
			ele.addChildElement("number1").setValue("12");
			ele.addChildElement("number2").setValue("13");
			
			SOAPMessage response=dispatch.invoke(message);
			//response.writeTo(System.out);
			NodeList nodeList=response.getSOAPBody().getElementsByTagName("result");
			Node node=nodeList.item(0);
			System.out.println(node.getTextContent());
			//使用此种方式也能够使用想要的值。
			
			
			
			
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SOAPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
}