我有一个spring-boot应用程序,正试图使用RestTemplate
调用另一家公司的rest服务。
远程Rest Service需要多个标头和正文内容作为Raw 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());