kelvincer
kelvincer

Reputation: 6138

Retrofit POST request to Spring Boot service

I am using Retrofit for post request to Spring Boot service but always is called failure Callback method. This is my simplified code:

Spring Boot service (Controller):

@RestController
public class ServController {

   @Autowired
   private UserRepository userRepository;

   @RequestMapping(value = "/user", method = RequestMethod.POST)
   public Boolean signUpUser(@RequestBody User user)
   {

      return true;
   }
}

My client interface:

public interface ChainApi {

    public static final String USER_PATH = "/user";

    @POST(USER_PATH)
    public void signUpUser(@Body User user, Callback<Boolean> callback);
}

Async POST request:

User user = new User();
user.setId(12);
user.setName(nameEtx.getText().toString());
user.setEmail(emailEtx.getText().toString());
user.setPassword(passwordEtx.getText().toString());

RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(Constant.URL_LOCALHOST)
            .build();

ChainApi service = restAdapter.create(ChainApi.class);

service.signUpUser(user, new Callback<Boolean>() {
    @Override
    public void success(Boolean aBoolean, Response response) {

        Log.i(TAG, "Succesfull");

    @Override
    public void failure(RetrofitError error) {

        Log.i(TAG, "Error " + error.getMessage()); // 400 Bad Request

    }
});

This is my User class(POJO):

@JsonIgnoreProperties(value = { "additionalProperties"})
public class User {

    @JsonProperty("id")
    private Integer id;
    @JsonProperty("name")
    private String name;
    @JsonProperty("password")
    private String password;
    @JsonProperty("email")
    private String email;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    // methods
}

NOTES: I am developing in Android and when make manual POST request from Postman I get 200 OK. In addition I get in logcat message: 400 Bad Request

Upvotes: 1

Views: 6836

Answers (1)

Miguel
Miguel

Reputation: 20123

Retrofit uses GSON as its default Converter. @JsonIgnoreProperties is an annotation from Jackson. Looking at your RestAdapter you don't seem to be specifying a Jackson Converter.

Square has implemented a JasksonConverter, you use it by including the dependency.

compile 'com.squareup.retrofit:converter-jackson:X.X.X'  

Use the version that matches your Retrofit version.

Then

JacksonConverter converter = JacksonConverter(new ObjectMapper());
RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(Constant.URL_LOCALHOST)
            .setConverter(converter)
            .build();

Upvotes: 2

Related Questions