zoukankan      html  css  js  c++  java
  • java 调用soap的简单例子(转载)

    [代码] OrderProcessor.java
    view source
    print?
    001    package javaxml2;
    002    
    003    import java.io.IOException;
    004    import java.io.StringWriter;
    005    import java.net.MalformedURLException;
    006    import java.net.URL;
    007    import java.util.Enumeration;
    008    import java.util.Hashtable;
    009    import java.util.Iterator;
    010    import java.util.LinkedList;
    011    import java.util.List;
    012    import java.util.Vector;
    013    import javax.mail.MessagingException;
    014    
    015    // DOM
    016    import org.w3c.dom.Do*****ent;
    017    import org.w3c.dom.Element;
    018    import org.w3c.dom.NodeList;
    019    import org.w3c.dom.Text;
    020    
    021    // SOAP imports
    022    import org.apache.soap.Constants;
    023    import org.apache.soap.Envelope;
    024    import org.apache.soap.Fault;
    025    import org.apache.soap.SOAPException;
    026    import org.apache.soap.encoding.SOAPMappingRegistry;
    027    import org.apache.soap.encoding.soapenc.BeanSerializer;
    028    import org.apache.soap.rpc.Call;
    029    import org.apache.soap.rpc.Parameter;
    030    import org.apache.soap.rpc.Response;
    031    import org.apache.soap.rpc.SOAPContext;
    032    import org.apache.soap.util.xml.QName;
    033    
    034    /**
    035     * <p>
    036     *  <code>OrderProcessor</code> is a web services client, and uses
    037     *    SOAP-RPC to interact with web services. However, it is also a
    038     *    web service, and receives SOAP messages and uses them to then
    039     *    construct SOAP-RPC calls, as well as sending return messages to
    040     *    its own web service clients.
    041     * </p>
    042     */
    043    public class OrderProcessor {
    044    
    045        /** Mapping for CD class */
    046        private SOAPMappingRegistry registry;
    047    
    048        /** The serializer for the CD class */
    049        private BeanSerializer serializer;
    050    
    051        /** The RPC Call object */
    052        private Call call;
    053    
    054        /** Parameters for call */
    055        private Vector params;
    056    
    057        /** Response from RPC call */
    058        private Response rpcResponse;
    059    
    060        /** The URL to connect to */
    061        private URL rpcServerURL;
    062    
    063        /**
    064         * <p>
    065         *  This will set up initial default values.
    066         * </p>
    067         */
    068        public void initialize() {
    069            // Set up internal URL for SOAP-RPC
    070            try {
    071                rpcServerURL =
    072                    new URL("http://localhost:8080/soap/servlet/rpcrouter");
    073            } catch (MalformedURLException neverHappens) {
    074                // ignored
    075            }
    076    
    077            // Set up a SOAP mapping to translate CD objects
    078            registry = new SOAPMappingRegistry();
    079            serializer = new BeanSerializer();
    080            registry.mapTypes(Constants.NS_URI_SOAP_ENC,
    081                new QName("urn:cd-catalog-demo", "cd"),
    082                CD.class, serializer, serializer);
    083    
    084            // Build a Call to the internal SOAP service
    085            call = new Call();
    086            call.setSOAPMappingRegistry(registry);
    087            call.setTargetObjectURI("urn:cd-catalog");
    088            call.setMethodName("getCD");
    089            call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
    090    
    091            // Set up input
    092            params = new Vector();
    093        }
    094    
    095        /**
    096         * <p>
    097         *  This method receives SOAP messages addressed to this web service,
    098         *    decodes those messages, and sends them to another web service
    099         *    via SOAP-RPC.
    100         * </p>
    101         *
    102         * @param env the SOAP envelope carrying the SOAP message.
    103         * @param req the SOAP request variable.
    104         * @param res the SOAP response variable.
    105         * @throws <code>IOException</code> - when errors result in connecting
    106         *         to the SOAP-RPC service.
    107         * @throws <code>MessagingException</code> - when errors occur
    108         *         in sending and receiving SOAP messages.
    109         */
    110        public void purchaseOrder(Envelope env, SOAPContext req, SOAPContext res)
    111            throws IOException, MessagingException {
    112    
    113            // Set up SOAP environment
    114            initialize();
    115    
    116            // Set up list of CDs successfully ordered
    117            List orderedCDs = new LinkedList();
    118    
    119            // Set up hashtable of failed orders
    120            Hashtable failedCDs = new Hashtable();
    121    
    122            // Get the purchaseOrder element - always the first body entry
    123            Vector bodyEntries = env.getBody().getBodyEntries();
    124            Element purchaseOrder = (Element)bodyEntries.iterator().next();
    125    
    126            // In a real application, do something with the buyer information
    127    
    128            // Get the CDs ordered
    129            Element order =
    130                (Element)purchaseOrder.getElementsByTagName("order").item(0);
    131            NodeList cds = order.getElementsByTagName("cd");
    132    
    133            // Loop through each ordered CD from the PO request
    134            for (int i=0, len=cds.getLength(); i<len; i++) {
    135                Element cdElement = (Element)cds.item(i);
    136                String artist = cdElement.getAttribute("artist");
    137                String title = cdElement.getAttribute("title");
    138    
    139                // Set up input
    140                params.clear();
    141                params.addElement(new Parameter("title", String.class, title, null));
    142                call.setParams(params);
    143    
    144                try {
    145                    // Invoke the call
    146                    rpcResponse = call.invoke(rpcServerURL, "");
    147    
    148                    if (!rpcResponse.generatedFault()) {
    149                        Parameter returnValue = rpcResponse.getReturnValue();
    150                        CD cd = (CD)returnValue.getValue();
    151    
    152                        // See if the CD is available
    153                        if (cd == null) {
    154                            failedCDs.put(title, "Requested CD is not available.");
    155                            continue;
    156                        }
    157    
    158                        // Verify it's by the right artist
    159                        if (cd.getArtist().equalsIgnoreCase(artist)) {
    160                            // Add this CD to the successful orders
    161                            orderedCDs.add(cd);
    162                        } else {
    163                            // Add this to the failed orders
    164                            failedCDs.put(title, "Incorrect artist for specified CD.");
    165                        }
    166                    } else {
    167                        Fault fault = rpcResponse.getFault();
    168                        failedCDs.put(title, fault.getFaultString());
    169                    }
    170                } catch (SOAPException e) {
    171                    failedCDs.put(title, "SOAP Exception: " + e.getMessage());
    172                }
    173            }
    174    
    175            // At the end of the loop, return something useful to the client
    176            Do*****ent doc = new org.apache.xerces.dom.Do*****entImpl();
    177            Element response = doc.createElement("response");
    178            Element orderedCDsElement = doc.createElement("orderedCDs");
    179            Element failedCDsElement = doc.createElement("failedCDs");
    180            response.appendChild(orderedCDsElement);
    181            response.appendChild(failedCDsElement);
    182    
    183            // Add the ordered CDs
    184            for (Iterator i = orderedCDs.iterator(); i.hasNext(); ) {
    185                CD orderedCD = (CD)i.next();
    186                Element cdElement = doc.createElement("orderedCD");
    187                cdElement.setAttribute("title", orderedCD.getTitle());
    188                cdElement.setAttribute("artist", orderedCD.getArtist());
    189                cdElement.setAttribute("label", orderedCD.getLabel());
    190                orderedCDsElement.appendChild(cdElement);
    191            }
    192    
    193            // Add the failed CDs
    194            Enumeration keys = failedCDs.keys();
    195            while (keys.hasMoreElements()) {
    196                String title = (String)keys.nextElement();
    197                String error = (String)failedCDs.get(title);
    198                Element failedElement = doc.createElement("failedCD");
    199                failedElement.setAttribute("title", title);
    200                failedElement.appendChild(doc.createTextNode(error));
    201                failedCDsElement.appendChild(failedElement);
    202            }
    203    
    204            // Set this as the content of the envelope
    205            bodyEntries.clear();
    206            bodyEntries.add(response);
    207            StringWriter writer = new StringWriter();
    208            env.marshall(writer, null);
    209    
    210            // Send the envelope back to the client
    211            res.setRootPart(writer.toString(), "text/xml");
    212        }
    213    }

  • 相关阅读:
    hdu4578线段树维护平方和,立方和(加,乘,赋值)或者珂朵莉树
    珂朵莉树(ODT老司机树)
    Codeforces Round #524 (Div. 2)D
    HDU1402 FFT高精度乘法模板题
    中国剩余定理poj1006
    POJ
    Install and Config MySQL 8 on Ubuntu
    Protobuf Examples
    Learning Thrift
    Flask Quickstart
  • 原文地址:https://www.cnblogs.com/ggbond1988/p/2268962.html
Copyright © 2011-2022 走看看