如何使用xml-正文将请求参数传递给post请求中的resttemplate?

时间:2018-10-23 21:19:59

标签: spring resttemplate

我尝试为spring-application控制器编写集成测试。

因此,此控制器可以接收带有xml正文和url中的params的post-请求。

我试图这样使用restTemplate:

HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);
        MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
        params.add("city", "London");
        params.add("street", "backer");
        params.add("house", "1");
        HttpEntity entity = new HttpEntity<>(user, headers);

        ResponseEntity responseEntity = restTemplate.postForEntity(
                String.format("%s/user", getServerAddress()),
                entity,
                Object.class,
                params
        );

因此,用户-xml映射到对象中。

在这种情况下会出现错误消息-服务器返回400空值。

但是,如果我从restTemplate参数中删除参数,并且在“?”之后的URL中删除了我的参数, -不会引发任何错误。

如何将参数传递给休息模板?

1 个答案:

答案 0 :(得分:1)

您可以使用jaxb编写XML的字符串表示形式,并将该字符串作为请求正文发送。 我认为您具有请求正文yourCusomObject的对象表示形式 使用jaxbMarshaller,可以将对象转换为String中的xml。

StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(yourCusomObject, sw);
String objectAsXmlString = sw.toString();

HttpEntity<String> entity = new HttpEntity<>(objectAsXmlString, headers);
ResponseEntity<String> response = restTemplate.postForEntity("/url", entity, String.class);

OP也想知道如何传递查询参数

http://MyHost:PORT/employee/{employee_id}

考虑这是我的url,它具有路径变量employee_id,我还需要向该url添加查询参数(?firstName=Abc&lastName=Pqr

这是您应该执行的操作。 代码给出了一个可以在restTemplate中使用的URI实例。

       String url = "http://MyHost:PORT/employee/{employee_id}";

        Map<String, String> uriParams = new HashMap<String, String>();
        uriParams.put("employee_id", "1231231");

        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
                // Add query parameter
                .queryParam("firstName", "Abc")
                .queryParam("lastName", "Pqr");

        URI urlWithParameters = builder.buildAndExpand(uriParams).toUri();
  

但是,请避免在POST中使用查询参数