如何在 Spring Boot RestTemplate 中将 body 内容作为原始 JSON 而不是 form-data 发送
How to send body content as raw JSON and not form-data in Spring Boot RestTemplate
我有一个 spring 引导应用程序并试图通过使用 RestTemplate
.
调用另一家公司的休息服务
远程 Rest 服务需要多个 header 和 body 内容作为 Raw JSON。
这是所需的示例 body 请求:
{
"amount": "10000",
"destinationNumber": "365412"
}
但是我的请求 body 是这样生成的:
{
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();
你能告诉我如何生成 body 请求作为 JSON 吗?
感谢@Alex Salauyou 根据他使用 HashMap 而不是 MultiValueMap 的评论解决了这个问题。以下是需要进行的更改:
HashMap<String, String> bodyParam = new HashMap<>();
bodyParam.put("amount", request.getAmount());
bodyParam.put("destinationNumber",request.getDestinationNumber());
我有一个 spring 引导应用程序并试图通过使用 RestTemplate
.
远程 Rest 服务需要多个 header 和 body 内容作为 Raw JSON。 这是所需的示例 body 请求:
{
"amount": "10000",
"destinationNumber": "365412"
}
但是我的请求 body 是这样生成的:
{
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();
你能告诉我如何生成 body 请求作为 JSON 吗?
感谢@Alex Salauyou 根据他使用 HashMap 而不是 MultiValueMap 的评论解决了这个问题。以下是需要进行的更改:
HashMap<String, String> bodyParam = new HashMap<>();
bodyParam.put("amount", request.getAmount());
bodyParam.put("destinationNumber",request.getDestinationNumber());