How to Send a SOAP Request to a Web Service in Java?

Question

How can I structure and send a SOAP request to a web service using Java?

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <getProductDetails xmlns="http://magazzino.example.com/ws">
      <productId>827635</productId>
    </getProductDetails>
  </soap:Body>
</soap:Envelope>

Answer

Sending a SOAP request to a web service in Java can be managed using packages like `javax.xml.soap`. SOAP (Simple Object Access Protocol) is a protocol for exchanging structured information in web services using XML. Below, we will explore how to structure a SOAP request, send it, and handle the response in Java.

import javax.xml.soap.*;

public class SoapClient {
    public static void main(String[] args) {
        try {
            // Create a SOAP Connection
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();

            String url = "http://yourWebServiceURL";
            SOAPMessage soapResponse = sendSoapRequest(soapConnection, url);
            soapConnection.close();

            // Process the SOAP Response
            soapResponse.writeTo(System.out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static SOAPMessage sendSoapRequest(SOAPConnection soapConnection, String url) throws SOAPException {
        // Create SOAP Message
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();

        SOAPPart soapPart = soapMessage.getSOAPPart();

        // Build SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("ns", "http://magazzino.example.com/ws");

        // Construct the SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("getProductDetails", "ns");
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("productId");
        soapBodyElem1.addTextNode("827635");

        soapMessage.saveChanges();

        // Send SOAP Message to SOAP Server
        return soapConnection.call(soapMessage, url);
    }
}

Causes

  • Understanding SOAP principles and XML structure is crucial.
  • Knowledge of Java libraries for SOAP communication is essential.

Solutions

  • Use the `javax.xml.soap` package to create and send SOAP requests.
  • Build the SOAP envelope with the necessary parameters and headers.

Common Mistakes

Mistake: Not including necessary namespaces in the SOAP envelope.

Solution: Ensure that all required namespaces are correctly declared in the SOAP envelope.

Mistake: Forgetting to set the content-type of the request header.

Solution: Set the correct content-type header to 'text/xml' when sending the request.

Helpers

  • SOAP request Java
  • Java web service
  • send SOAP request Java
  • SOAP API Java

Related Questions

⦿How to Calculate the Difference in Seconds Between Two Dates Using Joda-Time

Learn how to calculate the difference in seconds between two dates in Java using JodaTime. Stepbystep guide with code examples.

⦿How to Prevent Singleton Instance Creation via Reflection in Java

Learn how to effectively prevent instance creation of Singleton classes in Java even through reflection with expert techniques and code examples.

⦿How to Change the Shadow Color of Material Elevation in Android?

Learn how to dynamically change the shadow color of material elevation in Android using code. Stepbystep guide and code examples included.

⦿How Can I Set Up a Local SMTP Server for Java Email Testing?

Learn how to create a local SMTP server in Java for testing email functionalities without using external providers.

⦿How to Perform a POST Request with URL Encoded Data Using Spring RestTemplate

Learn how to send URL encoded data via a POST request using Spring RestTemplate including common mistakes and debugging tips.

⦿How to Fix 'Could Not Find Method testCompile()' Error in Gradle?

Learn how to resolve the Could not find method testCompile error in Gradle and understand the correct usage of dependencies in Gradle projects.

⦿What is the Difference Between 'if' and 'else if' Statements in Programming?

Explore the key differences between if and else if statements their usage and potential pitfalls in programming.

⦿Resolving Compile Errors in IntelliJ IDEA After Moving Classes Between Maven Modules

Learn how to fix compile errors in IntelliJ IDEA when moving classes between Maven modules despite successful command line builds.

⦿How to Adjust Font Size in Java's drawString Method

Learn how to change the font size for drawString in Java including code examples and troubleshooting tips.

⦿How to Generate a UUID with All Zeros in Java?

Learn how to create a UUID with all zeros in Java address common errors and explore UUID types such as MinValue and Invalid.

© Copyright 2025 - CodingTechRoom.com