如何使用 Spring RestTemplate 发送 XML POST 请求?

新手上路,请多包涵

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

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

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

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

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

原文由 membersound 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.8k
2 个回答

首先,定义您的 HTTP 标头,如下所示:

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

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

 headers.setContentType(MediaType.APPLICATION_XML);

然后定义一个 HttpEntityRequestEntity 来准备你的请求对象:

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

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

 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 .

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

原文由 Ali Dehghani 发布,翻译遵循 CC BY-SA 3.0 许可协议

在下面找到使用 RestTemplate 将 XML 交换为 String 并接收响应的示例:

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

原文由 Sam 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题