Enterprise Java

Posting XML Data with Spring RestTemplate

In modern microservice architectures, applications frequently communicate with external systems using REST APIs. While JSON is the most commonly used communication format, many enterprise systems such as banking, aviation, telecom, and legacy SOAP-based services still expect data in XML. Spring Boot provides a convenient way to send XML data using RestTemplate, allowing developers to serialize Java objects into XML and send them via HTTP POST requests. Let us delve into understanding how Spring RestTemplate XML POST requests work.

1. What is RestTemplate?

RestTemplate is a synchronous, blocking HTTP client provided by the Spring Framework. It is designed to make it easy for applications to communicate with RESTful services by abstracting away much of the underlying HTTP handling. Instead of manually constructing HTTP connections, writing XML/JSON serialization code, or managing connection streams, developers can rely on RestTemplate’s clean and intuitive API.

Even though RestTemplate is now in maintenance mode (with WebClient being the recommended successor in reactive environments), it remains extremely popular and widely used in enterprise applications, especially those that require:

  • Simple synchronous HTTP calls
  • XML-based communication with legacy systems
  • Straightforward request/response patterns
  • Integration with non-reactive Spring MVC applications

RestTemplate offers a wide set of methods to perform CRUD operations against HTTP endpoints. Some of the commonly used methods include:

  • postForObject(url, request, responseType) – Sends a POST request and returns the response body as an object.
  • postForEntity(url, request, responseType) – Similar to postForObject() but includes full HTTP response details (status, headers, body).
  • exchange(url, method, requestEntity, responseType) – A more flexible method that supports custom headers, HTTP methods, and request/response handling.

Under the hood, RestTemplate uses HttpMessageConverters to automatically convert Java objects to and from various media types (JSON, XML, form data, plain text). When XML support is enabled using JAXB or Jackson XML, RestTemplate can seamlessly serialize Java POJOs into XML payloads and send them as part of an HTTP request.

Because of its simplicity, predictability, and well-established usage patterns, RestTemplate continues to be an excellent choice for:

  • Calling external APIs from backend systems
  • Automating integration tasks
  • Inter-service communication within traditional microservices
  • Sending and receiving XML in enterprise workflows

In summary, RestTemplate is a powerful yet easy-to-use tool for synchronous REST interactions. It hides the complexity of HTTP, letting developers focus on business logic rather than networking details.

2. Code Example

2.1 Adding Dependencies (pom.xml)

To enable XML serialization and HTTP communication using RestTemplate, add the following essential Spring Boot dependencies to your project’s pom.xml.

<dependencies>
    <!-- Spring Web for RestTemplate -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- JAXB for XML serialization -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-xml</artifactId>
    </dependency>
</dependencies>

In this configuration, the spring-boot-starter-web dependency provides the required HTTP client support, including RestTemplate, while spring-boot-starter-xml activates JAXB-based XML marshalling and unmarshalling. Together, they allow Spring to automatically convert Java objects into XML payloads and seamlessly send them in HTTP requests.

2.2 XML DTO

The following Java class represents the XML payload model. It uses JAXB annotations to map Java fields to XML elements, allowing Spring to automatically convert the object into a well-structured XML document during the POST request.

// FlightRequest.java
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "FlightRequest")
public class FlightRequest {

    private String code;

    public FlightRequest() {}
    public FlightRequest(String code) { this.code = code; }

    @XmlElement(name = "FlightCode")
    public String getCode() { return code; }
    public void setCode(String code) { this.code = code; }
}

This class defines a simple XML structure where FlightRequest becomes the root tag and FlightCode represents a single nested element. The @XmlRootElement annotation tells Spring how to wrap the XML, while @XmlElement ensures that the code field is correctly serialized into the <FlightCode> tag when sending the HTTP POST request.

2.3 Simple Server Component to Receive XML POST

To demonstrate the complete end-to-end flow, let us create a very simple Spring Boot server component that receives the XML POST request and logs its contents. This helps verify that the XML sent by RestTemplate is correctly serialized, transmitted, and deserialized on the server side. The following REST controller exposes a POST endpoint that consumes XML, automatically converts it into the FlightRequest object, and logs the received payload.

// FlightController.java
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FlightController {

    @PostMapping(
        value = "/api/flights",
        consumes = MediaType.APPLICATION_XML_VALUE,
        produces = MediaType.TEXT_PLAIN_VALUE
    )
    public String receiveFlight(@RequestBody FlightRequest request) {

        System.out.println("Received XML Request");
        System.out.println("Flight Code: " + request.getCode());

        return "Flight request received successfully";
    }
}

2.4 Main Class

The following Spring Boot class uses CommandLineRunner to automatically send an XML-based POST request as soon as the application starts. This design is useful for testing integrations, running startup processes, or triggering background workflows without requiring a controller endpoint.

// XmlPostApp.java
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class XmlPostApp implements CommandLineRunner {

    private final RestTemplate restTemplate = new RestTemplate();

    public static void main(String[] args) {
        SpringApplication.run(XmlPostApp.class, args);
    }

    @Override
    public void run(String... args) {

        String url = "http://localhost:8080/api/flights";

        FlightRequest requestBody = new FlightRequest("AI-2025");

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);

        HttpEntity request =
                new HttpEntity(requestBody, headers);

        System.out.println("Sending XML POST to: " + url);

        String response =
                restTemplate.postForObject(url, request, String.class);

        System.out.println("Received Response:");
        System.out.println(response);
    }
}

In this code, the application defines a CommandLineRunner that executes immediately after Spring Boot starts. It constructs a FlightRequest object, sets the Content-Type to XML, wraps everything inside an HttpEntity, and uses RestTemplate to send a POST request to the target URL. The console logs both the outgoing request action and the response received from the server, making it easy to verify XML communication during application startup.

2.5 Code Run and Code Output

2.5.1 Code Run

Once the application is ready, you can run it directly from your IDE or by executing the Spring Boot JAR. Since both the XML client (RestTemplate) and the server endpoint are part of the same Spring Boot application, the CommandLineRunner will automatically trigger the XML POST request to the local server as soon as the application starts.

# If using Maven
mvn spring-boot:run

# Or if you packaged the jar
java -jar xml-post-app-0.0.1-SNAPSHOT.jar

The application will start, initialize the embedded web server on port 8080, expose the /api/flights endpoint, and immediately send an XML POST request to that endpoint.

2.5.2 Code Output

2.5.2.1 Client-side Logs
:: Spring Boot ::  (v3.x.x)

2025-01-12T10:15:23  INFO 12345 --- [           main] c.x.XmlPostApp : Starting XmlPostApp
Sending XML POST to: http://localhost:8080/api/flights
Received Response:
Flight request received successfully 
2.5.2.2 Server-side Logs
Received XML Request
Flight Code: AI-2025

The logs confirm that:

  • The Spring Boot application started successfully.
  • The CommandLineRunner sent an XML POST request using RestTemplate.
  • The local server endpoint received and deserialized the XML payload.
  • The request contents were logged on the server.
  • A response was returned to the client.

This verifies the complete XML POST lifecycle — from client serialization to server deserialization — without requiring any external systems.

Sign up

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button