spring - 如何在 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 吗?
解决方案
感谢@Alex Salauyou 基于他使用 HashMap 而不是 MultiValueMap 的评论解决了这个问题。以下是需要做的更改:
HashMap<String, String> bodyParam = new HashMap<>();
bodyParam.put("amount", request.getAmount());
bodyParam.put("destinationNumber",request.getDestinationNumber());
推荐阅读
- elasticsearch - 替换字段中的坏词并将结果保存回字段而不索引该字段
- django - Django 模型 - 在 Django ORM 上建模(Postgres-12 数据库视图)
- python - 将 3 个数组相乘以形成一个 3D 数组,其中条目相乘
- sql-server - 创建不对称键 '+@MANV+'
- deep-learning - 使用 PyTorch DistributedDataParallel 在多个节点上训练时进程卡住
- python-3.x - 我只想要函数的距离值
- function - 如何使用(def)函数内部的变量?
- android-recyclerview - 如何预加载像 instagram feed 这样的帖子
- python - 为什么硒不能点击元素?
- awk - 具有更多实例和空间的 awk 循环