Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send XML POST requests with Spring RestTemplate?

Tags:

java

spring

xml

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?

like image 822
membersound Avatar asked Feb 17 '16 15:02

membersound


People also ask

Can I send XML in REST API?

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.

Which method of RestTemplate is used for sending POST request?

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.

Can Rest return XML?

Data types that REST API can return are as follows: JSON (JavaScript Object Notation) XML.

Does RestTemplate use Okhttp?

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.


3 Answers

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 POSTing 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.

like image 142
Ali Dehghani Avatar answered Sep 16 '22 21:09

Ali Dehghani


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); 
like image 29
Sam Avatar answered Sep 17 '22 21:09

Sam


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();
    }
}
like image 39
ksokol Avatar answered Sep 20 '22 21:09

ksokol