membersound membersound - 1 year ago 286
Java Question

How to send XML POST requests with Spring RestTemplate?

Is it possible to send

requests with
, eg

I want to send the following xml to the url


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

How could I achieve this with spring?

Answer Source

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:


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download