meh
meh

Reputation: 22479

No suitable HttpMessageConverter found when trying to execute restclient request

I'm trying to use Spring for Android rest client to send data with an http post , to avoid creating and parsing the json data.

From their manual they have the following method:

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

After the method is called I get the following exception:

No suitable HttpMessageConverter found when trying to execute restclient request

My activity code snippet is :

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 is :

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 ?

Upvotes: 9

Views: 21108

Answers (3)

aazeem
aazeem

Reputation: 864

There could be a few different reasons why this can happen. In my case, i had the RestTemplate already wired in, but 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>

Upvotes: 7

Risadinha
Risadinha

Reputation: 16666

Your code looks fine in general. Maybe this is a version problem. Check whether you use Jackson 2, and if so, change the converter to MappingJackson2HttpMessageConverter.

No need for something like HttpMessageConverter<Message>.

On a side node: Java convention is to use lower casing for variable names. So, it would be more readable for other Java developers to do:

private String library;

public void setLibrary(String library) {
    this.library = library;
}

Upvotes: 1

John B
John B

Reputation: 32959

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

Upvotes: 6

Related Questions