【问题标题】:How to make a POST call using RestTemplate with a Json body and header? [duplicate]如何使用带有 Json 正文和标头的 RestTemplate 进行 POST 调用? [复制]
【发布时间】:2018-08-09 01:35:36
【问题描述】:

如何使用带有 Json 正文和标头的 RestTemplate 进行 POST 调用?我要发布的 Json 主体结构复杂。

{
    "foo": "long",
    "bar": {
        "foo": {
            "foo": [
                "long"
            ]
        },
        "fiz": [
            null
        ],
        "sides": [
            null
        ],
        "biz": ""
    },
    "biz": {
        "boo": "",
        "li": [
            null
        ],
        "biz": {
            "bzo": "",
            "lsp": ""
        },
        "baz": "",
        "bar": ""
    }
}

请求正文

【问题讨论】:

  • 不清楚你想要达到什么目的。而且您选择的标签似乎也不相关。
  • 嘿@Raptor,我想调用一个休息端点。使用上述响应正文发布电话
  • 你已经尝试了什么?

标签: java spring rest post resttemplate


【解决方案1】:

RestTemplate 提供exchange() 方法来调用其他HTTP url,以uri、HTTP 方法、HTTP 实体和响应类作为方法参数。

RestTemplate 的交换方法的签名是:

restTemplate.exchange(url, method, requestEntity, responseType);

例如:

//wrapping stringified request-body and HTTP request-headers into HTTP entity and passing it in exchange() method...    
HttpEntity<String> entity = new HttpEntity<>(requestBody, requestHeaders); 

restTemplate.exchange("http://localhost:8080/context-path/resource", HttpMethod.POST, entity, String.class);

如果您的 url 中有任何路径变量,那么 RestTemplate 还提供了接受 Map 作为路径变量的重写方法:

restTemplate.exchange(url, 方法, requestEntity, responseType, 路径变量);

【讨论】:

  • 嘿@Harsh 谢谢...如果我的 requestBody 是自定义对象怎么办? HttpEntity entity = new HttpEntity(Object, requestHeaders);抛出错误:“构造函数 HttpEntity(Object, HttpHeaders) 未定义”
  • @TheLastJedi,假设您的 requestBody 是一个自定义对象(例如 A 类的对象),那么您需要为您的自定义类启动 HttpEntity:例如:A a = new A( ); HttpEntity entity = new HttpEntity(a,requestHeaders);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-13
  • 2020-01-02
  • 2021-08-13
  • 2016-04-20
  • 2018-07-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多