Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...