Tips: Send and receive SOAP messages with JAXM

zhaozj2021-02-16  80

The basis for web services is to send and receive messages in standard format to make all systems understand. Typically, that format is a Simple Object Access Protocol (SOAP). SOAP messages can be manually generated and transmitted, but Java API (JAXM) for XML messages makes many required steps (such as creating connection or creation and sends active messages). This skill article records a synchronous SOAP message creation and sends.

This process includes creating a SOAP connection, creating a SOAP message, filling message, sending message, retrieving a response.

JAXM can be obtained as part of Java XML PACK (2002 Spring Edition) and Java Web Services Developer Pack EA2 (see Resources). The latter also includes a copy of the Tomcat web server and a sample application. One of those sample web services as the destination of SOAP messages in this skill article, the content and functions of the actual services in this example are not very important.

SOAP message structure

A basic SOAP message consists of a envelope containing two main parts (headers and mains). The application determines how to use these parts, but the entire message must follow a specific XML structure, for example:

Sample SOAP message 4/10/2002 Fun with Frogs

In this example, the header is empty, and the body contains information for the destination as a calendar application.

Please pay attention to the structure of this message. Envelope contains Header and Body elements, all of which are http://schemas.xmlsoap.org/soap/envelop/ namespace. The entire message will be sent to a web service through a SOAP connection.

Create connectivity and messages

The first step is to create a whole class and connection:

Create a connection

import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPConnection; public class SOAPTip {public static void main (String args []) {try {// First create the connection SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance (); SOAPCONNECTION CONNECTION = SOAPCONNFAATORY.CREATECONNECTION (); // close the connection ();} catch (excetion e) {system.out.println (E.getMessage ());}}}

SOAP messages can be sent directly by SOAPConnection or indirectly using the message delivery provider. In this example, the application creates a SOAPCONNECTION object by using the factory (Factory). The factory also creates a message itself:

Create a message object

import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPMessage; import javax.xml.soap.SOAPPart; import javax.xml. soap.SOAPEnvelope; import javax.xml.soap.SOAPBody; public class SOAPTip {public static void main (String args []) {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 (); // Create objects for the message parts sOAPPart soapPart = message.getSOAPPart (); SOAPEnvelope envelope = SOAPPART.GETENVELOPE (); soapbody body = envelope.getBody (); // close the connection connection.close ();} catch (excetion e) {system.out.println (E.getMessage ());}}}

First, create a message itself by using MessageFactory. This message already contains blank version of basic parts such as Envelope and Header. SOAPPART contains Envelope, and envelope contains the body. Create a reference to the desired object (such as soapbody).

Next, fill SOAPBODY:

Fill body ... import javax.xml.soap.soapbody; import javax.xml.soap.soaplelement; public class soaptip {public static void main (string args []) {Try {... // crete 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 ("Schedule", "CAL", "http://www.example.com/calendar")); // Add Content BodyElement.AddchildElement ("Cal: NewItem"). AddTextNode ("Contenthere"); //// Save the message message.savechanges (); // check the input system.out.println ("/ nRequest: / n"); message.writeto (system.out); system.out.println (); // Close THE Connection connection.close ();} catch (exception e) {system.out.println (E.GetMessage ());}}} The subject of the SOAP message is like any other XML element, you can add sub-elements in it (eg Schedule elements). Typically, you can use AddChildElement (ElementName), but the envelope.createname () method shown here simplifies the creation of elements using namespace declarations for data or payload. Indeed, create a schedule element to create a BodyElement SoapeElement object. The BodyElement object can then add its own text node to its own child elements Cal: NewItem. In this way, you can build an XML structure like the build any other XML document. However, using JAXM, you also have the opportunity to create a SOAPPART that directly creates a message directly using the external file. For example, the XML structure in the first list is stored in file prepped.msg, and it can call it to replace manually build a document.

Create a message from an external file ... import javax.xml.soap.SOAPElement; import java.io.FileInputStream; import javax.xml.transform.stream.StreamSource; public class SOAPTip {public static void main (String args []) { ... // Create objects for the message parts sOAPPart soapPart = message.getSOAPPart (); SOAPEnvelope envelope = soapPart.getEnvelope (); SOAPBody body = envelope.getBody (); // Populate the Message StreamSource preppedMsgSrc = new StreamSource (new FileInputStream ("preped.msg")); SOAPPART.SETCONTENT (PreppedMsgsrc); // Save the message message.saveChanges (); ...}} The result is the SOAP message that is ready to send. Send a message For synchronization messages, send SOAP messages and reception answers that occur in a single step:

Send message ... import javax.xml.Messaging.urlendPoint; public class soaptip {public static void main (string args [】) {... // check the input system.out.println ("/ nRequest: / n" ); message.writeto (system.out); system.out.println (); // send the message and get a reply // set the destination urlendpoint destination = new urlendpoint ("http: // localhost: 8080 / jaxm- SIMPLE / RECEIVER "); // send the message soapMessage reply = connection.call (message, destination); // close the connection connection.close (); ...}}

The actual message is sent using the call () method, which uses the message itself and the destination as a parameter, and then returns the second SOAPMESSAGE as a response. The destination must be an endpoint object, or UrlendPoint in this example. This example uses a sample servlet from JWSDP, which is only used to get a response. The call () method is always blocked until it receives the returned soapMessage.

response

Returned SOAPMESSAGE - Reply - is a SOAP message, which is the same as the sent message format, so it can operate it like any other XML message. SOAP allows you to convert answers directly by using XSLT:

Read response ... import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamResult; public class SOAPTip {public static Void Main (String Args []) {Try {... // send the message soapMessage reply = connection.call (message, destination); // check the output system.out.println ("/ nresponse: / n") ; // Create the transformer TransformerFactory transformerFactory = TransformerFactory.newInstance (); Transformer transformer = transformerFactory.newTransformer (); // Extract the content of the reply Source sourceContent = reply.getSOAPPart () getContent ();. // Set the output for the transformation StreamResult result = new StreamResult (System.out); transformer.transform (sourceContent, result); System.out.println (); // Close the connection connection.close (); ...}} as in any TRANSFORMER objects are created in the XSLT application. In this example, we only want to output content, so there is no style sheet. Here, the content itself is the entire SOAP portion of the message (different from the SOAP message that may contain attachments). You can also extract envelopes and mains before processing. The results in this example are just System.out, but it can be any option commonly used for conversion. Convert as usual.

Figure 1. SOAP request and response

Next step

While the endpoint in this example is a servlet that provides a static response, the actual response depends on the functionality of the service and the nature of the request. At the same time, although this skill article demonstrates the synchronous sending and reception of the message, by using the ProviderConnection object instead of SOAPConnection, JAXM allows asynchronous transmission using the message delivery provider. The provider has always saved this message until the message is successfully sent.

转载请注明原文地址:https://www.9cbs.com/read-17146.html

New Post(0)