首页 > 解决方案 > 如何在 Spring Boot RestTemplate 中将正文内容作为原始 JSON 而不是表单数据发送

问题描述

我有一个 Spring Boot 应用程序,并试图通过使用来调用另一家公司的休息服务RestTemplate

远程 Rest Service 需要多个标头和正文内容作为原始 JSON。这是所需的正文请求示例:

{ 
 "amount": "10000",
 "destinationNumber": "365412"
}

但我的请求正文生成如下:

{ 
 amount= [10000],
 destinationNumber= [365412]
}

我已经这样做了:

    String BASE_URI = "http://server.com/sericeX";
    RestTemplate template = new RestTemplate();

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Authorization","Some token");
    headers.add("Content-Type", "application/json");

    MultiValueMap<String, String> bodyParam = new LinkedMultiValueMap<>();
    bodyParam.add("amount", request.getAmount());
    bodyParam.add("destinationNumber",request.getDestinationNumber());

    HttpEntity entity = new HttpEntity(bodyParam,headers);

    ResponseEntity<TransferEntity> responseEntity = template.exchange(BASE_URI, HttpMethod.POST, entity,TransferEntity.class);
    TransferEntity transferEntity = responseEntity.getBody();

您能告诉我如何将正文请求生成为 JSON 吗?

标签: springspring-bootcontent-typeresttemplatespring-rest

解决方案


感谢@Alex Salauyou 基于他使用 HashMap 而不是 MultiValueMap 的评论解决了这个问题。以下是需要做的更改:

HashMap<String, String> bodyParam = new HashMap<>();
bodyParam.put("amount", request.getAmount());
bodyParam.put("destinationNumber",request.getDestinationNumber());

推荐阅读