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?
The REST API Client Service currently accepts only JSON input when making REST API Create, Read, Update, or Delete requests. It is nevertheless possible to use XML input when making REST API requests.
RestTemplate's postForObject method creates a new resource by posting an object to the given URI template. It returns the result as automatically converted to the type specified in the responseType parameter.
Data types that REST API can return are as follows: JSON (JavaScript Object Notation) XML.
Okhttp3 is a quite popular http client implementation for Java and we can easily embed it into Spring RestTemplate abstraction. Following bean declaration will make the default RestTemplete binding instance an Okhttp3 client. You can just autowire the Resttemplate to use this customized Okhttp3 based resttemplate.
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<String>(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 POST
ing the request to the http://localhost:8080/xml/availability
endpoint and converting the HTTP
response body into a String
.
Note, that in the above examples new HttpEntity<String>(...)
can be replaced with new HttpEntity<>(...)
using JDK7 and later.
Find below for example to use a RestTemplate to exchange XML as String and receive a response:
String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><AvailReq><hotelid>123</hotelid></AvailReq>"; RestTemplate restTemplate = new RestTemplate(); //Create a list for the message converters List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(); //Add the String Message converter messageConverters.add(new StringHttpMessageConverter()); //Add the message converters to the restTemplate restTemplate.setMessageConverters(messageConverters); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_XML); HttpEntity<String> request = new HttpEntity<String>(xmlString, headers); final ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8080/xml/availability", request, String.class);
Below you find a complete example how to use a RestTemplate
to exchange XML documents and receive a HTML response:
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.header;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import org.junit.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
public class XmlTest {
@Test
public void test() throws Exception {
RestTemplate restTemplate = new RestTemplate();
MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
String htmlString = "<p>response</p>";
String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><AvailReq><hotelid>123</hotelid></AvailReq>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xmlString)));
mockServer.expect(requestTo("http://localhost:8080/xml/availability"))
.andExpect(method(HttpMethod.POST))
.andExpect(content().string(is(xmlString)))
.andExpect(header("header", "value"))
.andRespond(withSuccess("<p>response</p>", MediaType.TEXT_HTML));
HttpHeaders headers = new HttpHeaders();
headers.add("header", "value");
HttpEntity<Document> request = new HttpEntity<>(document, headers);
final ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8080/xml/availability", request, String.class);
assertThat(response.getBody(), is(htmlString));
mockServer.verify();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With