如何使用带有Json主体和标头的RestTemplate进行POST调用?

时间:2018-03-01 03:05:01

标签: java spring rest post resttemplate

如何使用带有Json正文和标题的RestTemplate进行POST调用?我要张贴的Json身体有一个复杂的结构。

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

请求正文

1 个答案:

答案 0 :(得分:1)

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

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,method,requestEntity,responseType,   pathVariables);