Is it possible to send XML POST requests with spring, eg RestTemplate?
I want to send the following xml to the ur
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 = "response
";
String xmlString = "123 ";
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("response
", MediaType.TEXT_HTML));
HttpHeaders headers = new HttpHeaders();
headers.add("header", "value");
HttpEntity request = new HttpEntity<>(document, headers);
final ResponseEntity response = restTemplate.postForEntity("http://localhost:8080/xml/availability", request, String.class);
assertThat(response.getBody(), is(htmlString));
mockServer.verify();
}
}