I'm getting the following error in org.springframework.web.client.RestClientException: No HttpMessageConverter for java.util.HashMapwhen using rest template. Does anyone have any idea whats wrong?
Using java 1.8, spring 5.2.2, commons-logging 1.2.
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.client.RestTemplate;
public class testapi {
private static final String API_BASE_URL = "https://xyz/rest/ng";
private static RestTemplate template = new RestTemplate();
public static void main(String[] args)
throws Exception {
String token = login();
}
private static String login() {
Map<String, Object> payload = new HashMap<>();
payload.put("loginName", "abc.com");
payload.put("password", "xyz");
Map<String, Object> resp = template.postForObject(getUrl("/sessions"), payload, Map.class);
return (String) resp.get("token");
}
}
Error
Exception in thread "main" org.springframework.web.client.RestClientException: No HttpMessageConverter for java.util.HashMap
at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:964)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:740)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:677)
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:421)
at TestFormApis.login(testapis.java:117)
at TestFormApis.main(testapis.java:61)
You are using Spring's web client
RestTemplatein the non-Spring environment (at least, your example demonstrates that you run this test in the standard Java way).If you start a Spring application, it takes most configuration to itself, including adding converters (default converters from package
org.springframework.http.converter.*: ByteArrayHttpMessageConverter, StringHttpMessageConverter, ResourceHttpMessageConverter, AllEncompassingHttpMessageConverter, MappingJackson2XmlHttpMessageConverter, MappingJackson2HttpMessageConverter). Last one - for your case, RestTemplate uses inner Jackson for converting.So, if you want to use your sample, just add the specific converter.
More easier way - to add Jackson library and convert manually:
And use
strPayloadinRestTempatecalls.Or just start your application as Spring one.