在《用Soap消息调用Web Services(续)》这篇文章中介绍了如何在客户端发送Soap请求去调用服务器端的Web Service并输出服务器返回的结果,但还存在两个弱点,本文的目的就是对其进行改进,使得构造Soap请求发送到服务器端的流程完整。<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
上文的弱点有二:1)Soap请求是一个XML文件,而非灵活构造出来的。2)服务器端返回的结果仅仅是输出到控制台,而没有进行解析。
待构造的Soap请求:
< SOAP - ENV:Envelopexmlns:SOAP - ENV = " http://schemas.xmlsoap.org/soap/envelope/ " >
< SOAP - ENV:Header / >
< SOAP - ENV:Body >
< ns1:getFriendsListxmlns:ns1 = " http://pojo.test.com " >
< in0type = " int " > 1 < / in0>
< in1type = " int " > 0 < / in1>
< / ns1:getFriendsList>
< / SOAP-ENV:Body>
< / SOAP-ENV:Envelope>
< SOAP - ENV:Header / >
< SOAP - ENV:Body >
< ns1:getFriendsListxmlns:ns1 = " http://pojo.test.com " >
< in0type = " int " > 1 < / in0>
< in1type = " int " > 0 < / in1>
< / ns1:getFriendsList>
< / SOAP-ENV:Body>
< / SOAP-ENV:Envelope>
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class SoapParser
{
publicstaticvoidmain(String[]args)
{
doSoapPost();
}
publicstaticvoiddoSoapPost()
{
try
{
//Firstcreatetheconnection
SOAPConnectionFactorysoapConnFactory=SOAPConnectionFactory.newInstance();
SOAPConnectionconnection=soapConnFactory.createConnection();//创建连接
//Next,createtheactualmessage
MessageFactorymessageFactory=MessageFactory.newInstance();
SOAPMessagemessage=messageFactory.createMessage();//创建soap请求
//Createobjectsforthemessageparts
SOAPPartsoapPart=message.getSOAPPart();
SOAPEnvelopeenvelope=soapPart.getEnvelope();
SOAPBodybody=envelope.getBody();
////Populatethebody
////Createthemainelementandnamespace
SOAPElementbodyElement=body.addChildElement(envelope.createName("getFriendsList","ns1","http://pojo.test.com"));
//Addcontent
SOAPElementfirstElemnt=bodyElement.addChildElement("in0");
NamefirstName=envelope.createName("type");
firstElemnt.addAttribute(firstName,"int");
firstElemnt.addTextNode("1");
SOAPElementsecondElemnt=bodyElement.addChildElement("in1");
NamesecondName=envelope.createName("type");
secondElemnt.addAttribute(secondName,"int");
secondElemnt.addTextNode("0");
//Savethemessage
message.saveChanges();
//Checktheinput
message.writeTo(System.out);
System.out.println();
//Sendthemessageandgetareply
//Setthedestination
Stringdestination=
"http://192.168.1.10:8080/myTest/services/MyService";
//Sendthemessage
SOAPMessagereply=connection.call(message,destination);
if(reply!=null)
{
SOAPPartreplySP=reply.getSOAPPart();
SOAPEnvelopereplySE=replySP.getEnvelope();
SOAPBodyreplySB=replySE.getBody();
Sourcesource=reply.getSOAPPart().getContent();
Transformertransformer=TransformerFactory.newInstance().newTransformer();
ByteArrayOutputStreammyOutStr=newByteArrayOutputStream();
StreamResultres=newStreamResult();
res.setOutputStream(myOutStr);
transformer.transform(source,res);
Stringtemp=myOutStr.toString("UTF-8");
System.out.println(temp);
byte[]bytes=temp.getBytes("UTF-8");
ByteArrayInputStreamin=newByteArrayInputStream(bytes);
DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance();
DocumentBuilderdb=null;
Documentdoc=null;
db=dbf.newDocumentBuilder();
doc=db.parse(in);
ElementdocEle=doc.getDocumentElement();
NodeListnl=docEle.getElementsByTagName("ns2:FriendsList");
if(nl!=null&&nl.getLength()>0)
{
for(inti=0;i<nl.getLength();i++)
{
//gettheemployeeelement
Elementel=(Element)nl.item(i);
Stringname=getTextValue(el,"name");
intid=getIntValue(el,"userId");
System.out.println("name:"+name+"id:"+id);
}
}
}
//Closetheconnection
connection.close();
}
catch(Exceptione)
{
System.out.println(e.getMessage());
}
}
privatestaticStringgetTextValue(Elementele,StringtagName){
StringtextVal=null;
NodeListnl=ele.getElementsByTagName(tagName);
if(nl!=null&&nl.getLength()>0){
Elementel=(Element)nl.item(0);
textVal=el.getFirstChild().getNodeValue();
}
returntextVal;
}
privatestaticintgetIntValue(Elementele,StringtagName){
//inproductionapplicationyouwouldcatchtheexception
returnInteger.parseInt(getTextValue(ele,tagName));
}
privatestaticvoidparseXmlFile(StringfileName)
{
//getthefactory
DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance();
try{
//Usingfactorygetaninstanceofdocumentbuilder
DocumentBuilderdb=dbf.newDocumentBuilder();
//parseusingbuildertogetDOMrepresentationoftheXMLfile
Documentdom=db.parse(fileName);
}catch(ParserConfigurationExceptionpce){
pce.printStackTrace();
}catch(SAXExceptionse){
se.printStackTrace();
}catch(IOExceptionioe){
ioe.printStackTrace();
}
}
}
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class SoapParser
{
publicstaticvoidmain(String[]args)
{
doSoapPost();
}
publicstaticvoiddoSoapPost()
{
try
{
//Firstcreatetheconnection
SOAPConnectionFactorysoapConnFactory=SOAPConnectionFactory.newInstance();
SOAPConnectionconnection=soapConnFactory.createConnection();//创建连接
//Next,createtheactualmessage
MessageFactorymessageFactory=MessageFactory.newInstance();
SOAPMessagemessage=messageFactory.createMessage();//创建soap请求
//Createobjectsforthemessageparts
SOAPPartsoapPart=message.getSOAPPart();
SOAPEnvelopeenvelope=soapPart.getEnvelope();
SOAPBodybody=envelope.getBody();
////Populatethebody
////Createthemainelementandnamespace
SOAPElementbodyElement=body.addChildElement(envelope.createName("getFriendsList","ns1","http://pojo.test.com"));
//Addcontent
SOAPElementfirstElemnt=bodyElement.addChildElement("in0");
NamefirstName=envelope.createName("type");
firstElemnt.addAttribute(firstName,"int");
firstElemnt.addTextNode("1");
SOAPElementsecondElemnt=bodyElement.addChildElement("in1");
NamesecondName=envelope.createName("type");
secondElemnt.addAttribute(secondName,"int");
secondElemnt.addTextNode("0");
//Savethemessage
message.saveChanges();
//Checktheinput
message.writeTo(System.out);
System.out.println();
//Sendthemessageandgetareply
//Setthedestination
Stringdestination=
"http://192.168.1.10:8080/myTest/services/MyService";
//Sendthemessage
SOAPMessagereply=connection.call(message,destination);
if(reply!=null)
{
SOAPPartreplySP=reply.getSOAPPart();
SOAPEnvelopereplySE=replySP.getEnvelope();
SOAPBodyreplySB=replySE.getBody();
Sourcesource=reply.getSOAPPart().getContent();
Transformertransformer=TransformerFactory.newInstance().newTransformer();
ByteArrayOutputStreammyOutStr=newByteArrayOutputStream();
StreamResultres=newStreamResult();
res.setOutputStream(myOutStr);
transformer.transform(source,res);
Stringtemp=myOutStr.toString("UTF-8");
System.out.println(temp);
byte[]bytes=temp.getBytes("UTF-8");
ByteArrayInputStreamin=newByteArrayInputStream(bytes);
DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance();
DocumentBuilderdb=null;
Documentdoc=null;
db=dbf.newDocumentBuilder();
doc=db.parse(in);
ElementdocEle=doc.getDocumentElement();
NodeListnl=docEle.getElementsByTagName("ns2:FriendsList");
if(nl!=null&&nl.getLength()>0)
{
for(inti=0;i<nl.getLength();i++)
{
//gettheemployeeelement
Elementel=(Element)nl.item(i);
Stringname=getTextValue(el,"name");
intid=getIntValue(el,"userId");
System.out.println("name:"+name+"id:"+id);
}
}
}
//Closetheconnection
connection.close();
}
catch(Exceptione)
{
System.out.println(e.getMessage());
}
}
privatestaticStringgetTextValue(Elementele,StringtagName){
StringtextVal=null;
NodeListnl=ele.getElementsByTagName(tagName);
if(nl!=null&&nl.getLength()>0){
Elementel=(Element)nl.item(0);
textVal=el.getFirstChild().getNodeValue();
}
returntextVal;
}
privatestaticintgetIntValue(Elementele,StringtagName){
//inproductionapplicationyouwouldcatchtheexception
returnInteger.parseInt(getTextValue(ele,tagName));
}
privatestaticvoidparseXmlFile(StringfileName)
{
//getthefactory
DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance();
try{
//Usingfactorygetaninstanceofdocumentbuilder
DocumentBuilderdb=dbf.newDocumentBuilder();
//parseusingbuildertogetDOMrepresentationoftheXMLfile
Documentdom=db.parse(fileName);
}catch(ParserConfigurationExceptionpce){
pce.printStackTrace();
}catch(SAXExceptionse){
se.printStackTrace();
}catch(IOExceptionioe){
ioe.printStackTrace();
}
}
}