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
I had a similar issue and was with it for 2 days. Below was my stacktrace.
java.lang.NullPointerException
at java.nio.charset.Charset.put(Charset.java:538)
at java.nio.charset.Charset.access$200(Charset.java:271)
at java.nio.charset.Charset$3.run(Charset.java:584)
at java.nio.charset.Charset$3.run(Charset.java:573)
at java.security.AccessController.doPrivileged(Native Method)
at java.nio.charset.Charset.availableCharsets(Charset.java:572)
at org.springframework.http.converter.StringHttpMessageConverter.getAcceptedCharsets(StringHttpMessageConverter.java:119)
at org.springframework.http.converter.StringHttpMessageConverter.writeInternal(StringHttpMessageConverter.java:103)
at org.springframework.http.converter.StringHttpMessageConverter.writeInternal(StringHttpMessageConverter.java:41)
The root cause was in the availableCharsets() static method in Charset class. One of the charset provider was returning a null iterator and the below piece of code i.hasNext() was throwing a null pointer exception.
private static void put(Iterator<Charset> i, Map<String,Charset> m) {
while (i.hasNext()) {
Charset cs = i.next();
if (!m.containsKey(cs.name()))
m.put(cs.name(), cs);
}
}
If you backtrace the stacktrace call, the StringHttpMessageConverter.writeInternal() method checks the writeAcceptCharset boolean and then calls the getAcceptedCharsets() from where Charset static method is called. To avoid this call, add the below lines.
StringHttpMessageConverter stringHttpMessageConverter=new StringHttpMessageConverter(Charset.forName("UTF-8"));
stringHttpMessageConverter.setWriteAcceptCharset(false);
responseEntity=restTemplate.exchange(requestUrl.toString(), HttpMethod.GET,request, <your_class>.class);
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);