Search code examples
javaspringkubernetesresttemplate

resttemplate.exchange throws null pointer exception


restTemplate.postForEntity(url,entity, String.class);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

Throws null pointer exception when trying to create an object.

I checked entity and url, it is getting printed in Logger message. But at this line it throws null pointer exception, but the object is still getting created..

If the object is getting created how can this throw null pointer exception..

I am using kubernetes, when i check command line in kubernetes it says object got created..but in logs it shows null pointer exception


Solution

  • The problem seem to be that you are executing the request two times.

    restTemplate.postForEntity(url, entity, String.class);
    ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
    

    Both postForEntity and exchange are sending a post request to your url. postForEntity can be seen as a specific case for the exchange method. See the documentation

    Please use only one of them, for example:

    ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);