Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:
Sending XML POST Requests with Spring RestTemplate
Last updated: November 15, 2025
1. Overview
Despite the rise of JSON and REST APIs, XML remains deeply embedded in enterprise systems. Many financial institutions, healthcare providers, government agencies, and legacy platforms continue to rely on SOAP services and XML-based protocols for system-to-system communication. When modern Spring Boot applications need to integrate with these established systems, developers must bridge the gap between contemporary development practices and traditional XML-based interfaces.
In this article, we demonstrate how to send XML POST requests, convert Java objects to XML, deserialize XML responses, and implement a clean service layer for XML-based integration.
2. Understanding RestTemplate and XML Support
RestTemplate implements Spring’s synchronous HTTP client using a blocking I/O model, where threads wait for the full request to complete. This approach suits enterprise transaction processing requiring sequential execution, such as payment authorization, contract validation, and document verification workflows.
To work with XML payloads, Spring uses HTTP message converters. These components serialize Java objects into XML when sending requests and convert XML into Java objects when receiving responses. Spring Boot automatically configures these converters when an appropriate XML library is present. In this article, we use the Jackson XML module, which offers efficient XML support with minimal configuration.
3. Project Setup and Dependencies
To work with XML in Spring Boot, we include the Spring Web starter for RestTemplate and the Jackson XML module. Spring Boot detects the XML module and registers the required message converters for XML serialization and deserialization.
Let’s add the following Maven spring-boot-starter-web and jackson-dataformat-xml dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
To use RestTemplate with dependency injection, we need to define it as a bean:
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
4. Creating XML Mapping Models
Before sending or receiving XML, we define Java classes that represent our XML payloads. Just like with JSON, simple POJOs can be serialized and deserialized automatically without any special annotations.
However, enterprise XML integrations often rely on explicit element names and root structures defined by external systems or XSD schemas. By adding Jackson’s XML annotations, we make the mapping predictable and aligned with the expected XML schema, which is a common requirement in industries such as banking, insurance, and government services.
Instead of constructing raw XML strings manually, we let Jackson handle conversion based on these annotations. This keeps our code maintainable, type-safe, and consistent with the structure of the XML message.
In this example, we model a simple payment interaction: our system sends payment instructions and expects a response confirming the result.
4.1. XML Request Model
The request model contains information about a payment transaction. Each class field corresponds to an XML element:
@JacksonXmlRootElement(localName = "PaymentRequest")
public class PaymentRequest {
@JacksonXmlProperty(localName = "transactionId")
private String transactionId;
@JacksonXmlProperty(localName = "amount")
private Double amount;
@JacksonXmlProperty(localName = "currency")
private String currency;
@JacksonXmlProperty(localName = "recipient")
private String recipient;
public PaymentRequest() {
}
public PaymentRequest(String transactionId, Double amount, String currency, String recipient) {
this.transactionId = transactionId;
this.amount = amount;
this.currency = currency;
this.recipient = recipient;
}
// getters and setters omitted for brevity
}
This class will be automatically serialized into XML. With the values above, it would produce:
<PaymentRequest>
<transactionId>TXN12345</transactionId>
<amount>1500.00</amount>
<currency>USD</currency>
<recipient>John Smith</recipient>
</PaymentRequest>
4.2. XML Response Model
The response model reflects the structure returned by the external system:
@JacksonXmlRootElement(localName = "PaymentResponse")
public class PaymentResponse {
@JacksonXmlProperty(localName = "status")
private String status;
@JacksonXmlProperty(localName = "message")
private String message;
@JacksonXmlProperty(localName = "referenceNumber")
private String referenceNumber;
public PaymentResponse() {
}
public PaymentResponse(String status, String message, String referenceNumber) {
this.status = status;
this.message = message;
this.referenceNumber = referenceNumber;
}
// getters and setters omitted for brevity
}
Spring will deserialize the XML into this model when receiving the response.
5. Implementing the XML Client Service
To keep the application structure clean, we implement a dedicated service that handles XML conversion and HTTP communication. Other components will interact only with Java objects, not XML or HTTP-specific logic.
We consolidate the logic into a single method that handles both sending the request and processing the response:
@Service
public class PaymentService {
private final RestTemplate restTemplate;
public PaymentService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public PaymentResponse processPayment(PaymentRequest request, String paymentUrl) {
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
HttpEntity<PaymentRequest> entity = new HttpEntity<>(request, headers);
ResponseEntity<PaymentResponse> response =
restTemplate.postForEntity(paymentUrl, entity, PaymentResponse.class);
return response.getBody();
} catch (Exception ex) {
throw new RuntimeException("Payment processing failed: " + ex.getMessage(), ex);
}
}
}
This consolidated approach simplifies the API so that callers use a single method to manage the entire payment flow. XML conversion happens transparently, with Spring handling serialization and deserialization behind the scenes. The design also centralizes error handling and maintains a clean separation of concerns while remaining flexible for future enhancements such as logging, timeouts, or retry logic.
6. Testing the XML Client Service
To verify that our XML client behaves correctly, we write unit tests for the PaymentService using Mockito. Each test focuses on a specific behavior: successful XML processing, server-side validation errors, and correct XML header setup. By mocking RestTemplate, we simulate external API behavior without calling a real server, making our tests fast and reliable.
The first test verifies the happy path scenario: when we submit a valid request, the service should receive a successful XML response, parse it into a PaymentResponse object, and return it to the caller:
@Test
void givenValidPaymentRequest_whenProcessPayment_thenReturnSuccessfulResponse() {
PaymentRequest request = new PaymentRequest("TXN001", 100.50, "USD", "Jane Doe");
PaymentResponse expectedResponse = new PaymentResponse(
"SUCCESS", "Payment processed successfully", "REF12345"
);
ResponseEntity<PaymentResponse> mockResponse =
new ResponseEntity<>(expectedResponse, HttpStatus.OK);
when(restTemplate.postForEntity(eq(testUrl), any(HttpEntity.class), eq(PaymentResponse.class)))
.thenReturn(mockResponse);
PaymentResponse actualResponse = paymentService.processPayment(request, testUrl);
assertNotNull(actualResponse);
assertEquals("SUCCESS", actualResponse.getStatus());
assertEquals("REF12345", actualResponse.getReferenceNumber());
assertEquals("Payment processed successfully", actualResponse.getMessage());
verify(restTemplate).postForEntity(eq(testUrl), any(HttpEntity.class), eq(PaymentResponse.class));
}
In this scenario, we mock a successful XML exchange. The test confirms that the service correctly returns the response object populated from the XML payload. We also verify that RestTemplate was called once to ensure correct request invocation.
Next, we simulate the case where the external system rejects the request — for example, due to invalid data. In this situation, RestTemplate throws a HttpClientErrorException, and our service must wrap this cleanly and provide a meaningful error message:
@Test
void givenRemoteServiceReturnsBadRequest_whenProcessPayment_thenThrowMeaningfulException() {
PaymentRequest request = new PaymentRequest("TXN002", 200.0, "EUR", "John Smith");
when(restTemplate.postForEntity(eq(testUrl), any(HttpEntity.class), eq(PaymentResponse.class)))
.thenThrow(new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Invalid amount"));
RuntimeException exception = assertThrows(RuntimeException.class,
() -> paymentService.processPayment(request, testUrl));
assertTrue(exception.getMessage().contains("Payment processing failed"));
assertTrue(exception.getMessage().contains("Invalid amount"));
}
Here, we simulate a 400 Bad Request returned by the API. Our test checks that the service does not silently fail or return null, but instead throws a clear, descriptive exception that includes the server-side error message.
Finally, some XML APIs require strict header values. Accordingly, this test verifies that our client correctly sets the Content-Type and Accept headers to application/xml:
Ultimately, this test confirms correct XML contract compliance by inspecting request headers passed to RestTemplate. Therefore, ensuring XML headers are present reduces compatibility issues with real-world XML APIs.
7. Conclusion
XML remains essential in enterprise systems, and Spring Boot with RestTemplate provides a clean approach for XML integration. Using annotated Java models and a dedicated service layer, modern applications can seamlessly communicate with legacy systems while maintaining code clarity.
As always, the full source code of the article is available over on GitHub.
















