Java > Java Networking > HTTP and Web Services > SOAP vs REST APIs

Java SOAP Client Example

This snippet demonstrates how to consume a SOAP web service using Java. It uses the `javax.xml.soap` package, which is part of the standard Java API (JAX-WS). It showcases sending a SOAP request and printing the SOAP response.

Code Snippet

This code performs the following steps:

  1. Imports necessary classes: Imports classes from `javax.xml.soap` and `javax.xml.namespace`.
  2. Creates a `SOAPConnection`: `SOAPConnectionFactory` is used to create a connection to the SOAP endpoint.
  3. Creates a `SOAPMessage`: `MessageFactory` creates a SOAP message.
  4. Builds the SOAP Envelope and Body: The code constructs the SOAP envelope, adds namespaces, and creates the SOAP body with the `` element and its child elements (`intA`, `intB`). This forms the actual SOAP request.
  5. Sets the SOAP Action: The `soapAction` header is set to indicate the operation to be performed.
  6. Sends the SOAP message: `soapConnection.call()` sends the message to the SOAP endpoint and retrieves the response.
  7. Prints the response: The response SOAP message is printed to the console.
  8. Extracts data from the response: The code retrieves the `` element from the SOAP body and extracts the result value.

import javax.xml.soap.*;
import javax.xml.namespace.QName;

public class SoapClientExample {

    public static void main(String[] args) throws Exception {
        // SOAP Endpoint URL
        String url = "http://www.dneonline.com/calculator.asmx";
        String soapAction = "http://tempuri.org/Add";

        // Create SOAP Connection
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();

        // Create SOAP Message
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();

        // Create SOAP Envelope
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("tem", "http://tempuri.org/");

        // Create SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement add = soapBody.addChildElement("Add", "tem");
        SOAPElement intA = add.addChildElement("intA", "tem");
        intA.addTextNode("5");
        SOAPElement intB = add.addChildElement("intB", "tem");
        intB.addTextNode("3");

        soapMessage.saveChanges();

        /* Print the request message */
        System.out.print("Request SOAP Message = ");
        soapMessage.writeTo(System.out);
        System.out.println();

        // Send SOAP Message to SOAP Server
        SOAPMessage soapResponse = soapConnection.call(soapMessage, url);

        // Print the SOAP Response
        System.out.print("Response SOAP Message = ");
        soapResponse.writeTo(System.out);
        System.out.println();

        // Extract data from SOAP Response
        SOAPBody responseBody = soapResponse.getSOAPBody();
        QName returnName = new QName("http://tempuri.org/", "AddResult");
        SOAPElement addResult = (SOAPElement) responseBody.getChildElements(returnName).next();

        String result = addResult.getValue();
        System.out.println("Result: " + result);

        soapConnection.close();
    }
}

Concepts Behind the Snippet

This snippet illustrates key concepts in SOAP web service consumption:

  • SOAP: Simple Object Access Protocol is a messaging protocol for exchanging structured information in the implementation of web services.
  • WSDL: Web Services Description Language is an XML-based interface definition language that is used for describing the functionality offered by a web service.
  • SOAP Envelope: The root element of a SOAP message, containing the SOAP header and body.
  • SOAP Header: Contains information such as authentication credentials or transaction identifiers.
  • SOAP Body: Contains the actual data being exchanged.
  • Namespaces: Used to avoid naming conflicts between elements from different XML vocabularies.

Real-Life Use Case

SOAP is often used in enterprise environments for integrating legacy systems or when strong security and reliability are required. For example, financial institutions might use SOAP for transaction processing or healthcare providers might use it for exchanging patient information.

Best Practices

  • Error Handling: Wrap the SOAP calls in `try-catch` blocks to handle potential `SOAPExceptions`.
  • WSDL Parsing: Use a WSDL parser to automatically generate the Java code for interacting with the SOAP service. This simplifies the process of creating SOAP messages and extracting data from responses.
  • Security: Implement appropriate security measures such as WS-Security to protect sensitive data exchanged via SOAP.
  • Logging: Log SOAP requests and responses for debugging and auditing purposes.

Interview Tip

When discussing SOAP, be prepared to explain the differences between SOAP and REST, the role of WSDL, and the structure of a SOAP message (Envelope, Header, Body). Also, be ready to discuss the advantages and disadvantages of SOAP compared to REST.

When to use them

SOAP is a better choice when you need guaranteed message delivery, strong security, transaction support, and formal contracts (WSDL). However, it's more complex and resource-intensive than REST.

Alternatives

  • REST APIs: A simpler and more lightweight alternative to SOAP.
  • gRPC: A high-performance, open-source universal RPC framework.
  • GraphQL: A query language for your API that allows clients to request only the data they need.

Pros

  • Standardized: SOAP has a formal standard (WSDL) that defines the interface.
  • Security: Supports WS-Security for robust security.
  • Reliability: Supports WS-ReliableMessaging for guaranteed message delivery.
  • Transaction support: Supports WS-Transaction for ACID transactions.

Cons

  • Complex: SOAP is more complex to implement and understand than REST.
  • Verbose: SOAP messages are typically larger than REST messages due to the XML format.
  • Resource-intensive: Parsing XML can be more resource-intensive than parsing JSON.
  • Less flexible: Changes to the service interface require updating the WSDL and regenerating client code.

FAQ

  • What is a WSDL file?

    A WSDL (Web Services Description Language) file is an XML document that describes a web service. It specifies the service's operations, input and output parameters, and the location of the service.
  • Do I need a WSDL file to use a SOAP service?

    While not strictly mandatory in all cases, it's highly recommended. The WSDL provides a contract, making it easier to generate client code and understand the service's capabilities. Without a WSDL, you'll need to manually construct the SOAP requests and parse the responses, which can be error-prone.
  • How can I generate client code from a WSDL file?

    You can use tools like `wsimport` (part of the JDK) or Apache CXF to generate Java classes from a WSDL file. These tools will create the necessary classes for sending SOAP requests and processing SOAP responses.