不使用LinkedMultiValueMap将请求正文传递到Spring Rest模板

问题描述 投票:0回答:2

我正在使用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内部服务器错误,所以我的问题是,如何获得[ 'account'属性是对象而不是数组?例如,我希望请求正文显示为:

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

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

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

任何对此的帮助将是盛大的!非常感谢

java spring httprequest resttemplate
2个回答
0
投票

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

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

检查https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/HttpEntity.html了解更多信息。


0
投票

答案实际上只是使用常规的HashMap而不是MultiValueMap。如此处所示,当您要将数组添加到请求正文中的单个键时,将使用MultiValueMap大小写。感谢您提供的所有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.