membersound membersound - 1 month ago 14
Java Question

How to send XML POST requests with Spring RestTemplate?

Is it possible to send

XML
POST
requests with
spring
, eg
RestTemplate
?

I want to send the following xml to the url
localhost:8080/xml/availability


<AvailReq>
<hotelid>123</hotelid>
</AvailReq>


Also do I want to add custom http headers on each request dynamically(!).

How could I achieve this with spring?

Answer

First of all, define your HTTP headers, like following:

HttpHeaders headers = new HttpHeaders();
headers.add("header_name", "header_value");

You can set any HTTP header with this approach. For well known headers you can use pre-defined methods. For example, in order to set Content-Type header:

headers.setContentType(MediaType.APPLICATION_XML);

Then define a HttpEntity or RequestEntity to prepare your request object:

HttpEntity<String> request = new HttpEntity<>(body, headers);

If you somehow have access to the XML string, you can use HttpEntity<String>. Otherwise you can define a POJO corresponding to that XML. and finally send the request using postFor... methods:

ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8080/xml/availability", request, String.class);

Here i'm POSTing the request to the http://localhost:8080/xml/availability endpoint and converting the HTTP response body into a String.

Comments