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

3
  • 2
    It's unclear what you want to achieve. And the tags you selected seem unrelated as well.
    – Raptor
    Mar 1, 2018 at 3:05
  • Hey @Raptor , I want to invoke a rest endpoint. Post call with above mentioned Response body
    – newb
    Mar 1, 2018 at 3:10
  • 2
    And what have you tried already?
    – Jason
    Mar 1, 2018 at 3:43

1 Answer 1

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

2
  • Hey @Harsh Thanks...What if my requestBody is a custom object? HttpEntity<String> entity = new HttpEntity<>(Object, requestHeaders); throws the error : "constructor HttpEntity<String>(Object, HttpHeaders) is undefined"
    – newb
    Mar 1, 2018 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<A> entity = new HttpEntity<>(a,requestHeaders); Mar 5, 2018 at 9:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.