非常感謝孫浩老師。
soap消息的分析
IMyService.java
package cn.lichen.webservice;
import javax.jws.WebService;
@WebService
public interface IMyService {
public int add(int a,int b);
public int minus(int a,int b);
}
修改過後:IMyService.java
package cn.lichen.webservice;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
@WebService
public interface IMyService {
@WebResult(name="addResult")
public int add(@WebParam(name="a")int a,@WebParam(name="b")int b);
public int minus(int a,int b);
}
消息的創建
package cn.lichen.soap;
import java.io.IOException;
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 org.junit.Test;
public class TestSoap {
@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.創建SOAPBoby
SOAPBody body = envelope.getBody();
//6.創建Qname,Qname就是帶有命名空間的節點 表示<xsd:add
QName name = new QName("http://www.lichen.cn/webservice", "add", "xsd");
//7.添加body節點元素
SOAPBodyElement bodyElement = body.addBodyElement(name);
//8.添加節點內容
bodyElement.addChildElement("a").setValue("123");
bodyElement.addChildElement("b").setValue("456");
//9.打印輸出
message.writeTo(System.out);
} catch (SOAPException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
置於xml文檔中:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header />
<SOAP-ENV:Body>
<xsd:add xmlns:xsd="http://www.lichen.cn/webservice">
<a>123</a>
<b>456</b>
</xsd:add>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>