构造Soap请求调用Web Services(三)

简介:

 在《用Soap消息调用Web Services(续)》这篇文章中介绍了如何在客户端发送Soap请求去调用服务器端的Web Service并输出服务器返回的结果,但还存在两个弱点,本文的目的就是对其进行改进,使得构造Soap请求发送到服务器端的流程完整。

      上文的弱点有二:1)Soap请求是一个XML文件,而非灵活构造出来的。2)服务器端返回的结果仅仅是输出到控制台,而没有进行解析。
      待构造的Soap请求:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<ns1:getFriendsList xmlns:ns1="http://pojo.test.com">
<in0 type="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 
{
    
    public static void main(String[] args)
    {
        doSoapPost();
    }

    public static void doSoapPost()
    {
        try 
        {
             //First create the connection
             SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance();
             SOAPConnection connection = soapConnFactory.createConnection();//创建连接
             
             //Next, create the actual message
             MessageFactory messageFactory = MessageFactory.newInstance();
             SOAPMessage message = messageFactory.createMessage();//创建soap请求
             
             //Create objects for the message parts            
             SOAPPart soapPart = message.getSOAPPart();
             SOAPEnvelope envelope = soapPart.getEnvelope();
             SOAPBody body = envelope.getBody();       
             
//             //Populate the body
//             //Create the main element and namespace
             SOAPElement bodyElement = body.addChildElement(envelope.createName("getFriendsList" , "ns1", "http://pojo.test.com"));
             //Add content
             SOAPElement firstElemnt = bodyElement.addChildElement("in0");
             Name firstName = envelope.createName("type");
             firstElemnt.addAttribute(firstName, "int");
             firstElemnt.addTextNode("1");

             SOAPElement secondElemnt = bodyElement.addChildElement("in1");
             Name secondName = envelope.createName("type");
             secondElemnt.addAttribute(secondName, "int");
             secondElemnt.addTextNode("0");
                   
             //Save the message
             message.saveChanges();
             //Check the input
             message.writeTo(System.out);
             System.out.println();
            //Send the message and get a reply   
                
            //Set the destination
            String destination = 
                  "http://192.168.1.10:8080/myTest/services/MyService";
            //Send the message
            SOAPMessage reply = connection.call(message, destination);
            
            if(reply!=null)
            {
                 SOAPPart replySP = reply.getSOAPPart();
                 SOAPEnvelope replySE = replySP.getEnvelope();
                 SOAPBody replySB = replySE.getBody();

                 Source source = reply.getSOAPPart().getContent();
                 Transformer transformer = TransformerFactory.newInstance().newTransformer();
                 ByteArrayOutputStream myOutStr = new ByteArrayOutputStream();
                 StreamResult res = new StreamResult();
                 res.setOutputStream(myOutStr);
                 transformer.transform(source,res);
                 String temp = myOutStr.toString("UTF-8");
                
                 System.out.println(temp);
                 byte[] bytes = temp.getBytes("UTF-8");
                 ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                 
                 DocumentBuilderFactory dbf =  DocumentBuilderFactory.newInstance();
                 DocumentBuilder db = null;
                 Document doc = null;
                 db = dbf.newDocumentBuilder();
                 doc = db.parse(in);
                 Element docEle = doc.getDocumentElement();
                 NodeList nl = docEle.getElementsByTagName("ns2:FriendsList");
                if(nl != null && nl.getLength() > 0) 
                {
                    for(int i = 0 ; i < nl.getLength();i++) 
                    {
                        //get the employee element
                        Element el = (Element)nl.item(i);
                        String name = getTextValue(el,"name");
                        int id = getIntValue(el,"userId");
                        System.out.println("name: "+name+" id: "+id);
                    }
                }    
            }
             //Close the connection            
             connection.close();
        } 
        catch(Exception e) 
        {
                System.out.println(e.getMessage());
        }   
    }
    

    /**
     * I take a xml element and the tag name, look for the tag and get
     * the text content 
     * i.e for <employee><name>John</name></employee> xml snippet if
     * the Element points to employee node and tagName is name I will return John  
     * @param ele
     * @param tagName
     * @return
     */
    private static String getTextValue(Element ele, String tagName) {
        String textVal = null;
        NodeList nl = ele.getElementsByTagName(tagName);
        if(nl != null && nl.getLength() > 0) {
            Element el = (Element)nl.item(0);
            textVal = el.getFirstChild().getNodeValue();
        }
        return textVal;
    }
    /**
     * Calls getTextValue and returns a int value
     * @param ele
     * @param tagName
     * @return
     */
    private static int getIntValue(Element ele, String tagName) {
        //in production application you would catch the exception
        return Integer.parseInt(getTextValue(ele,tagName));
    }
    
    private static void parseXmlFile(String fileName)
    {
        //get the factory
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            //Using factory get an instance of document builder
            DocumentBuilder db = dbf.newDocumentBuilder();
            //parse using builder to get DOM representation of the XML file
            Document dom = db.parse(fileName);
        }catch(ParserConfigurationException pce) {
            pce.printStackTrace();
        }catch(SAXException se) {
            se.printStackTrace();
        }catch(IOException ioe) {
            ioe.printStackTrace();
        }
    }
}



本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2008/05/21/1203941.html,如需转载请自行联系原作者
目录
相关文章
|
1月前
|
存储 开发框架 JSON
在 Python 中,如何处理 Web 请求和响应?
【2月更文挑战第26天】【2月更文挑战第90篇】在 Python 中,如何处理 Web 请求和响应?
|
3月前
|
前端开发 JavaScript API
阿里云智能媒体服务IMS(Intelligent Media Services)的视频剪辑Web SDK
【1月更文挑战第15天】【1月更文挑战第72篇】阿里云智能媒体服务IMS(Intelligent Media Services)的视频剪辑Web SDK
54 6
|
5月前
[Web程序设计]实验: 请求与响应
[Web程序设计]实验: 请求与响应
|
2月前
|
存储 网络协议 Linux
《网络是怎么样连接的》读书笔记 - WEB服务端请求和响应(五)
《网络是怎么样连接的》读书笔记 - WEB服务端请求和响应(五)
36 0
|
3月前
|
前端开发 数据库 Python
使用 Python 的 Web 框架(如 Django 或 Flask)来建立后端接口,用于处理用户的请求,从数据库中查找答案并返回给前端界面
【1月更文挑战第13天】使用 Python 的 Web 框架(如 Django 或 Flask)来建立后端接口,用于处理用户的请求,从数据库中查找答案并返回给前端界面
85 7
|
1月前
|
XML 安全 数据安全/隐私保护
探索 SOAP:揭开 Web 服务的神秘面纱(下)
探索 SOAP:揭开 Web 服务的神秘面纱(下)
|
1月前
|
XML 开发框架 JSON
探索 SOAP:揭开 Web 服务的神秘面纱(上)
探索 SOAP:揭开 Web 服务的神秘面纱(上)
|
4月前
|
存储 网络协议 Linux
《网络是怎么样连接的》读书笔记 - WEB服务端请求和响应(五)
《网络是怎么样连接的》读书笔记 - WEB服务端请求和响应(五)
28 0
《网络是怎么样连接的》读书笔记 - WEB服务端请求和响应(五)
|
7月前
|
安全 中间件 API
详解Django请求与响应:深入理解Web Http交互的核心机制
详解Django请求与响应:深入理解Web Http交互的核心机制
73 0
|
19天前
|
监控 JavaScript 前端开发
《理解 WebSocket:Java Web 开发的实时通信技术》
【4月更文挑战第4天】WebSocket是Java Web实时通信的关键技术,提供双向持久连接,实现低延迟、高效率的实时交互。适用于聊天应用、在线游戏、数据监控和即时通知。开发涉及服务器端实现、客户端连接及数据协议定义,注意安全、错误处理、性能和兼容性。随着实时应用需求增加,WebSocket在Java Web开发中的地位将更加重要。