【问题标题】:How to send body content as raw JSON and not form-data in Spring Boot RestTemplate如何在 Spring Boot RestTemplate 中将正文内容作为原始 JSON 而不是表单数据发送
【发布时间】:2018-11-13 13:44:23
【问题描述】:

我有一个 Spring Boot 应用程序并尝试使用 RestTemplate 调用另一家公司的休息服务。

远程 Rest 服务需要多个标头和正文内容作为原始 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 吗?

【问题讨论】:

  • 试着把这个headers.add("Content-Type", "application/json")改成headers.add("Content-Type", "text/json");
  • 谢谢,我做了,但没有区别。
  • 尝试使用HashMap 而不是MultiValueMap 代替bodyParam

标签: spring spring-boot content-type resttemplate spring-rest


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-01
    • 2016-10-14
    • 2019-02-02
    • 2014-02-05
    • 2017-10-09
    • 2023-03-09
    • 2020-05-10
    • 2019-03-19
    相关资源
    最近更新 更多