0

How to make a POST call using RestTemplate with a Json body and header? The Json body I want to post has a complex structure.

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

Request Body

newb
  • 13
  • 1
  • 5

1 Answers1

1

RestTemplate provides exchange() method to call other HTTP urls with uri, HTTP methods, HTTP entity and response-class as method parameters.

Signature of RestTemplate's exchange method is:

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

For e.g. :

//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);

In case you have any path-variables in your url, then RestTemplate also provides overridden method which accepts Map for path-variables:

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

Harsh Mehta
  • 571
  • 3
  • 16
  • Hey @Harsh Thanks...What if my requestBody is a custom object? HttpEntity entity = new HttpEntity<>(Object, requestHeaders); throws the error : "constructor HttpEntity(Object, HttpHeaders) is undefined" – newb Mar 01 '18 at 22:37
  • @TheLastJedi, let's say if your requestBody is a custom object (e.g. an object of Class A), then you need to initiate HttpEntity<> for your custom class: e.g.: A a = new A(); HttpEntity entity = new HttpEntity<>(a,requestHeaders); – Harsh Mehta Mar 05 '18 at 09:26