不使用LinkedMultiValueMap将请求主体传递给Spring Rest模板

时间:2020-01-15 15:09:39

标签: java spring httprequest resttemplate

我正在使用Spring Rest模板发出Http PUT请求,直到现在我一直在使用以下内容传递请求正文:

        MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>();
        body.add("account", testAccount);

        HttpEntity<?> requestEntity = new HttpEntity<Object>(body, headers);

        ResponseEntity<String> responseEntity;

        try {
            responseEntity = rest.exchange(uri, HttpMethod.PUT, requestEntity, String.class);
        }
        catch (HttpStatusCodeException e) {
            log.error("Http PUT failed with response: " + e.getStatusText());
            return ResponseEntity.status(e.getStatusCode()).body(e.getResponseBodyAsString());
        }

        return responseEntity; 

发送到我的目标API的请求正文显示为:

{"account":[{"account_id":"495"}]}

这有效,但是我的目标API并不期望account对象将数组作为值,并且当前给我500 Internal Server Error,所以我的问题是,我如何获得该值'account'属性的值是对象而不是数组?例如,我希望请求正文显示为:

{"account":{"account_id":"495"}}

是否可以使用另一种类型的Map,它不接受多个值?

如果可能的话,我仍然想使用exchange方法。

任何在此方面获得帮助的人都是伟大的!非常感谢

1 个答案:

答案 0 :(得分:0)

您不需要使用MultiValueMap。您可以简单地使用

HttpEntity<Account> requestEntity = new HttpEntity<>(testAccount, headers);

检查Java API for JSON Processing - Getting Started以获得更多信息。