No suitable HttpMessageConverter was found when trying to execute restclient request

I am trying to use Spring for Android rest client to send data using http post to avoid creating and parsing json data.

In their manual, they have the following method:

 restTemplate.postForObject(url, m, String.class) 

After calling the method, I get the following exception:

 No suitable HttpMessageConverter found when trying to execute restclient request 

My activity code snippet:

 RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); restTemplate.getMessageConverters().add(new StringHttpMessageConverter()); Message m = new Message(); m.setLibrary("1"); m.setPassword("1395"); m.setUserName("1395"); String result = restTemplate.postForObject(url, m, String.class); 

And the Message object:

 public class Message { private String UserName, Password, Library; public String getUserName() { return UserName; } public void setUserName(String userName) { UserName = userName; } public String getPassword() { return Password; } public void setPassword(String password) { Password = password; } public String getLibrary() { return Library; } public void setLibrary(String library) { Library = library; } } 

Why can't it convert the Message object to JSON ?

+8
java android
source share
3 answers

It looks like you have not added the Message specific HttpMessageConverter . HttpMessageConverter is an interface . You need to create a class that implements HttpMessageConverter<Message> , and add an instance of this class to RestTemplate through restTemplate.getMessageConverters().add(new MyMessageConverter());

+6
source

There may be several different reasons why this may happen. In my case, I already had RestTemplate connected, but it still got this error. Turns out I had to add a dependency on "jackson-databind":

 <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> 
+5
source

In general, your code looks fine. Perhaps this is a version issue. Check if you are using Jackson 2, and if so, change the converter to MappingJackson2HttpMessageConverter .

No need for something like HttpMessageConverter<Message> .

On the node side: The Java convention is to use a lower case for variable names. So for other Java developers, this would be more readable:

 private String library; public void setLibrary(String library) { this.library = library; } 
+1
source

All Articles