如何使用Spring RestTemplate发送XML POST请求? [英] How to send XML POST requests with Spring RestTemplate?

查看:1266
本文介绍了如何使用Spring RestTemplate发送XML POST请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 spring XML POST 请求c>,例如 RestTemplate

Is it possible to send XML POST requests with spring, eg RestTemplate?

我想将以下xml发送到网址 localhost:8080 / xml / availability

I want to send the following xml to the url localhost:8080/xml/availability

<AvailReq>
  <hotelid>123</hotelid>
</AvailReq>

我还想动态地在每个请求上添加自定义http标头(!)。

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

我怎样才能用春天实现这个目标?

How could I achieve this with spring?

推荐答案

首先,定义你的 HTTP 标题,如下所示:

First of all, define your HTTP headers, like following:

HttpHeaders headers = new HttpHeaders();
headers.add("header_name", "header_value");

您可以使用此设置任何 HTTP 标头做法。对于众所周知的标头,您可以使用预定义的方法。例如,为了设置 Content-Type 标题:

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);

然后定义 HttpEntity RequestEntity 准备您的请求对象:

Then define a HttpEntity or RequestEntity to prepare your request object:

HttpEntity<String> request = new HttpEntity<String>(body, headers);

如果您以某种方式访问​​ XML 字符串,您可以使用 HttpEntity< String> 。否则,您可以定义与 XML 对应的POJO。最后使用 postFor ...发送请求方法:

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);

这里我 POST 请求到 http:// localhost:8080 / xml / availability 端点并将 HTTP 响应主体转换为字符串

Here i'm POSTing the request to the http://localhost:8080/xml/availability endpoint and converting the HTTP response body into a String.

注意,在上面的例子中 new HttpEntity< String>(... )可以使用JDK7及更高版本替换为 new HttpEntity<>(...)

Note, that in the above examples new HttpEntity<String>(...) can be replaced with new HttpEntity<>(...) using JDK7 and later.

这篇关于如何使用Spring RestTemplate发送XML POST请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆