import java.io.IOException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
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.Document;
public class TestSoap {
private String ns="http://service.soap.org/";
private String wsdlUrl="http://localhost:6666/ns?wsdl";
@Test
public void test01(){
try {
//1
创建消息工厂
MessageFactory
factory=MessageFactory.newInstance();
//2 根据消息工厂创建soapmessage
SOAPMessage
message=factory.createMessage();
//3
创建SOAPPart
SOAPPart
part=message.getSOAPPart();
//4
获取SOAPEnvelope
SOAPEnvelope
envelope=part.getEnvelope();
//5 可以通过SOAPEnvelope有效的获取相应的body和header等消息
SOAPBody
body=envelope.getBody();
//6
根据qname创建相应的节点
QName
qname=new QName("http://java.zttc.edu.cn/webservice");
///body.addBodyElement(qname).setValue("1234234");
SOAPBodyElement ele= body.addBodyElement(qname);
ele.addChildElement("a").setValue("22");
ele.addChildElement("b").setValue("33");
//打印消息信息
message.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 test02(){
try {
//1
创建服务
URL url=new
URL(wsdlUrl);
QName
sname=new QName(ns, "MyServiceImplService");
Service
service=Service.create(url,sname);
//2
创建dispatch
Dispatch
dispatch=service.createDispatch(new
QName(ns,"MyServiceImplPort"),
SOAPMessage.class,
Service.Mode.MESSAGE);
//3
创建SOAPMessage
SOAPMessage
msg=MessageFactory.newInstance().createMessage();
SOAPEnvelope
envelope=msg.getSOAPPart().getEnvelope();
SOAPBody
body=envelope.getBody();
//4
创建qname并指定消息中的传递数据
QName
ename=new QName(ns,"add","nn");
SOAPBodyElement
ele=body.addBodyElement(ename);
ele.addChildElement("a").setValue("22");
ele.addChildElement("b").setValue("33");
msg.writeTo(System.out);
System.out.println("\n
invoking..");
//5
通过dispatch传递消息
SOAPMessage
response=dispatch.invoke(msg);
response.writeTo(System.out);
System.out.println();
//将响应的消息转为dom对象
Document
doc=response.getSOAPPart().getEnvelope().getBody().extractContentAsDocument();
String
str=doc.getElementsByTagName_r("addResult").item(0).getTextContent();
System.out.println(str);
} catch (Exception e) {
// TODO
Auto-generated catch block
e.printStackTrace();
}
}
}
测试test02,结果: