eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Introduction

When working with SOAP-based web services in Java, there are situations where accessing the raw XML of a SOAP message becomes necessary. We may need it for debugging integration issues, logging requests and responses for auditing, validating message structure, or troubleshooting interoperability problems between systems.

Although SOAP frameworks hide most XML processing from us, real-world projects often require visibility into the actual SOAP envelope that is being exchanged. The approach we use depends on the SOAP stack in our application, such as SAAJ, JAX-WS, Apache CXF, or Spring Web Services.

In this article, we’ll explore the most practical ways to retrieve raw XML from SOAP messages in Java. We’ll examine different frameworks, explain when to use each method, and highlight important considerations to avoid common pitfalls.

2. What Do We Mean by Raw XML

Before implementing any solution, we should clarify what raw XML means in this context. Depending on the requirement, it may refer to:

  • The full SOAP envelope, including Header and Body
  • Only the SOAP body payload
  • The exact byte stream sent over HTTP

In most cases, retrieving the SOAP envelope as a string is sufficient for logging and debugging. However, if we require exact byte-level accuracy for compliance or forensic logging, we may need to intercept the transport layer instead of relying solely on framework-level APIs.

With that clarification in mind, let’s examine the most common implementation approaches.

3. Using SAAJ and SOAPMessage

If we’re working directly with SOAPMessage, extracting the raw XML is straightforward. The message can be written into an output stream and converted into a string.

Let’s consider the following example:

public static String soapMessageToString(SOAPMessage message) {
    try {
        if (message == null) {
            throw new IllegalArgumentException("SOAPMessage cannot be null");
        }
        message.saveChanges();

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        message.writeTo(out);

        return out.toString(StandardCharsets.UTF_8.name());
    } catch (Exception e) {
        throw new RuntimeException("Failed to convert SOAPMessage to String", e);
    }
}

In this example, we call saveChanges() to ensure that any modifications to the SOAP headers or body are applied before serialization. The writeTo(OutputStream) method writes the complete SOAP envelope, including header and body, into the ByteArrayOutputStream.

Finally, we convert the output stream into a UTF-8 string representation. This approach is simple and reliable for logging and debugging purposes.

4. Using JAX-WS with SOAPHandler

When we use JAX-WS, the cleanest way to capture raw SOAP XML is to plug into the message pipeline with a SOAPHandler. To keep the code generic and suitable for unit testing, we should not print directly. Instead, we can forward captured XML to a small interface that we can later implement using any logging framework, persistence layer, or test recorder.

Let’s consider the following example:

public class RawSoapCaptureHandler implements SOAPHandler<SOAPMessageContext> {

    public interface SoapXmlSink {
        void accept(Direction direction, String soapXml);
    }

    public enum Direction {
        OUTBOUND,
        INBOUND,
        FAULT
    }

    private final SoapXmlSink sink;

    public RawSoapCaptureHandler(SoapXmlSink sink) {
        this.sink = sink;
    }

    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        Boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        Direction direction = Boolean.TRUE.equals(outbound) ? Direction.OUTBOUND : Direction.INBOUND;

        String xml = toString(context.getMessage());
        sink.accept(direction, xml);
        return true;
    }

    @Override
    public boolean handleFault(SOAPMessageContext context) {
        String xml = toString(context.getMessage());
        sink.accept(Direction.FAULT, xml);
        return true;
    }

    @Override
    public void close(MessageContext context) {
    }

    @Override
    public Set<QName> getHeaders() {
        return Collections.emptySet();
    }

    private String toString(SOAPMessage message) {
        try {
            message.saveChanges();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            message.writeTo(out);
            return out.toString(StandardCharsets.UTF_8.name());
        } catch (Exception e) {
            throw new RuntimeException("Failed to serialize SOAP message", e);
        }
    }
}

In this implementation, we intercept both inbound and outbound SOAP messages using handleMessage(), and we intercept SOAP faults using handleFault(). We determine the message direction using MESSAGE_OUTBOUND_PROPERTY, then serialize the SOAP envelope with SOAPMessage.writeTo(OutputStream).

Instead of printing, we pass the raw XML to SoapXmlSink. This keeps the handler framework-neutral and easy to test. In unit tests, we can provide a sink that stores messages in memory. In production, we can provide a sink that forwards the XML to a logger, a database, or a monitoring system.

5. Using Apache CXF Interceptors

If our application uses Apache CXF, the framework provides built-in interceptors that simplify SOAP message logging.

Let’s consider the following example:

Client client = ClientProxy.getClient(port);

client.getInInterceptors().add(new LoggingInInterceptor());
client.getOutInterceptors().add(new LoggingOutInterceptor());

In this case, we obtain the CXF Client from the generated service proxy. We then register LoggingInInterceptor and LoggingOutInterceptor.

These interceptors automatically log the full SOAP envelope for incoming and outgoing messages. CXF internally manages stream buffering to avoid the risk of accidentally consuming the message stream.

6. Using Spring Web Services

When we use Spring Web Services, we can capture SOAP XML using a ClientInterceptor. As with the JAX-WS handler, we should avoid printing and forward the raw XML to a generic sink so that we can plug in logging or tests later.

Let’s consider the following example:

public class SpringSoapCaptureInterceptor implements ClientInterceptor {

    public interface SoapXmlSink {
        void accept(Direction direction, String soapXml);
    }

    public enum Direction {
        REQUEST,
        RESPONSE,
        FAULT
    }

    private final SoapXmlSink sink;

    public SpringSoapCaptureInterceptor(SoapXmlSink sink) {
        this.sink = sink;
    }

    @Override
    public boolean handleRequest(MessageContext messageContext) {
        String xml = toString(messageContext.getRequest());
        sink.accept(Direction.REQUEST, xml);
        return true;
    }

    @Override
    public boolean handleResponse(MessageContext messageContext) {
        String xml = toString(messageContext.getResponse());
        sink.accept(Direction.RESPONSE, xml);
        return true;
    }

    @Override
    public boolean handleFault(MessageContext messageContext) {
        String xml = toString(messageContext.getResponse());
        sink.accept(Direction.FAULT, xml);
        return true;
    }

    private String toString(WebServiceMessage message) {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            message.writeTo(out);
            return out.toString(StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("Failed to serialize Spring WS message", e);
        }
    }
}

In this example, we capture the raw SOAP XML for requests, responses, and faults. Spring WS provides the message as a WebServiceMessage, and the writeTo(OutputStream) method serializes the full SOAP envelope.

By forwarding the XML to SoapXmlSink, we keep the interceptor generic and reusable. We can later connect it to our preferred logging framework, or we can plug in a test sink that asserts the captured XML without relying on console output.

7. Important Considerations

When retrieving raw SOAP XML, several important factors must be considered.

First, encoding is typically UTF-8, but we should verify it if byte-level accuracy is required. Additionally, some frameworks rely on internal input streams. If we read from a stream without proper buffering, we may consume it and disrupt further processing.

Beyond technical handling, logging full SOAP messages in production environments may impact performance and increase memory usage. For this reason, it is best to enable detailed logging conditionally.

Finally, we must consider security. SOAP envelopes may contain sensitive information such as authentication tokens or personal data. Therefore, we must ensure proper log sanitization and compliance with security policies.

We should also be cautious when handling very large SOAP messages. Serializing large payloads into memory using ByteArrayOutputStream may increase memory consumption in high-throughput systems. In such cases, we should evaluate streaming or size-limited logging strategies.

8. Conclusion

Retrieving raw XML from a SOAP message in Java is a common requirement in enterprise systems. Whether we work directly with SOAPMessage, intercept messages using JAX-WS handlers, or rely on framework-specific solutions such as Apache CXF interceptors, the underlying principle remains the same. We serialize the SOAP envelope safely and convert it into a readable format.

By understanding these techniques, we gain deeper insight into SOAP communication and improve our ability to debug, monitor, and maintain service integrations effectively.

As always, the complete source code for the tutorial is available over on GitHub.

Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
guest
0 Comments
Oldest
Newest
Inline Feedbacks
View all comments