Implementing SOAP Web Service Calls in Java: Methods and Best Practices

Nov 11, 2025 · Programming · 13 views · 7.8

Keywords: Java | SOAP | Web Services | SAAJ | JAX-WS | Spring Web Services

Abstract: This article provides an in-depth exploration of two primary approaches for invoking SOAP web services in Java: using the wsimport tool for client code generation and manual SOAP client construction. Through detailed code examples and architectural analysis, it covers SAAJ framework applications, XML serialization techniques, and Spring Web Services integration, offering developers comprehensive solutions for SOAP service consumption.

Overview of SOAP Web Service Invocation

In modern distributed system architectures, SOAP (Simple Object Access Protocol) web services serve as a mature enterprise-grade solution widely adopted for inter-system communication. The Java platform offers multiple technology stacks to support SOAP service consumption, allowing developers to choose appropriate implementation paths based on specific requirements.

wsimport Tool Approach

Utilizing the wsimport tool represents the standardized method for invoking SOAP services. This tool automatically generates client code from WSDL (Web Services Description Language) documents, including service interfaces, data binding classes, and related helper classes. In Maven projects, automated generation can be achieved through configuration of the jaxws-maven-plugin:

<plugin>
    <groupId>com.sun.xml.ws</groupId>
    <artifactId>jaxws-maven-plugin</artifactId>
    <version>3.0.0</version>
    <executions>
        <execution>
            <goals>
                <goal>wsimport</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <packageName>com.example.consumingwebservice.wsdl</packageName>
        <wsdlUrls>
            <wsdlUrl>http://localhost:8080/ws/countries.wsdl</wsdlUrl>
        </wsdlUrls>
    </configuration>
</plugin>

The primary advantage of this approach lies in code standardization and maintainability, though it may result in duplicate class definitions when business classes already exist. Developers must balance between code duplication and standardization requirements.

Custom SOAP Client Implementation

For scenarios requiring greater flexibility, manual SOAP client construction provides finer control. This method primarily consists of two core components: HTTP communication handling and XML serialization.

SAAJ Framework Application

SAAJ (SOAP with Attachments API for Java) is a built-in SOAP message processing framework in Java SE, offering comprehensive capabilities for SOAP message construction and parsing. Below is a complete SAAJ client implementation example:

import javax.xml.soap.*;

public class SOAPClientSAAJ {
    
    public static void callTemperatureService() {
        String endpoint = "https://www.w3schools.com/xml/tempconvert.asmx";
        String action = "https://www.w3schools.com/xml/CelsiusToFahrenheit";
        
        try {
            SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
            SOAPConnection connection = factory.createConnection();
            
            SOAPMessage request = createTemperatureRequest(action);
            SOAPMessage response = connection.call(request, endpoint);
            
            // Process response
            response.writeTo(System.out);
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private static SOAPMessage createTemperatureRequest(String soapAction) throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage message = messageFactory.createMessage();
        
        SOAPPart soapPart = message.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("temp", "https://www.w3schools.com/xml/");
        
        SOAPBody body = envelope.getBody();
        SOAPElement operation = body.addChildElement("CelsiusToFahrenheit", "temp");
        SOAPElement parameter = operation.addChildElement("Celsius", "temp");
        parameter.addTextNode("100");
        
        MimeHeaders headers = message.getMimeHeaders();
        headers.addHeader("SOAPAction", soapAction);
        message.saveChanges();
        
        return message;
    }
}

This implementation demonstrates the complete SOAP message construction process, including namespace declaration, message body creation, and HTTP header configuration. Developers can adjust the message structure according to specific service WSDL definitions.

JAXB Serialization Integration

Integrating JAXB (Java Architecture for XML Binding) in custom clients enables automatic conversion between business objects and XML. Spring Framework's Jaxb2Marshaller provides convenient configuration for this purpose:

@Configuration
public class WebServiceConfig {
    
    @Bean
    public Jaxb2Marshaller marshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setContextPath("com.example.webservice.model");
        return marshaller;
    }
    
    @Bean
    public WebServiceTemplate webServiceTemplate(Jaxb2Marshaller marshaller) {
        WebServiceTemplate template = new WebServiceTemplate();
        template.setMarshaller(marshaller);
        template.setUnmarshaller(marshaller);
        template.setDefaultUri("http://localhost:8080/ws");
        return template;
    }
}

Spring Web Services Integration

The Spring Web Services framework offers higher-level abstractions that simplify SOAP service consumption. By extending the WebServiceGatewaySupport class, service clients can be rapidly implemented:

public class CountryClient extends WebServiceGatewaySupport {
    
    public GetCountryResponse getCountry(String countryName) {
        GetCountryRequest request = new GetCountryRequest();
        request.setName(countryName);
        
        return (GetCountryResponse) getWebServiceTemplate()
            .marshalSendAndReceive("http://localhost:8080/ws/countries", 
                                 request,
                                 new SoapActionCallback("http://spring.io/guides/GetCountryRequest"));
    }
}

This approach benefits from Spring's dependency injection and configuration management while providing robust exception handling and logging mechanisms.

Architectural Design and Best Practices

When selecting SOAP service invocation solutions, the following architectural considerations should be addressed:

Service Contract Stability: For services with stable interfaces, wsimport-generated client code offers better long-term maintainability. For frequently changing services, manual clients provide greater flexibility.

Performance Considerations: Custom clients typically demonstrate better performance by avoiding potential redundancies in auto-generated code, though this difference is often negligible in enterprise applications.

Error Handling: SOAP service invocations require comprehensive error handling mechanisms, including network exceptions, timeout control, retry logic, and SOAP fault parsing. The Spring Web Services framework provides excellent support in this area.

Practical Application Scenarios

In the car service example mentioned at the article's beginning, the following concise API can be implemented:

public class Car {
    private String color;
    private WebServiceTemplate webServiceTemplate;
    
    public Car(String color) {
        this.color = color;
    }
    
    public void webMethod() {
        CarServiceRequest request = new CarServiceRequest();
        request.setColor(this.color);
        
        CarServiceResponse response = (CarServiceResponse) 
            webServiceTemplate.marshalSendAndReceive(request);
        
        // Process business logic
        updateFromResponse(response);
    }
}

This design achieves the simple invocation interface desired by developers while maintaining proper architectural separation.

Conclusion

The Java platform offers multiple mature technical solutions for SOAP web service invocation. Development teams should select the most appropriate implementation based on specific project requirements, team technology stacks, and service characteristics. Whether choosing the standardized wsimport approach or flexible manual client implementation, ensuring code maintainability, error handling capabilities, and performance remains crucial. While RESTful API usage continues to grow with microservices architecture adoption, SOAP maintains significant value in scenarios requiring strong type contracts and WS-* standard support.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.