POST with Android Retrofit POST with Android Retrofit android android

POST with Android Retrofit


One of the benefits of Retrofit is not having to parse the JSON yourself. You should have something like:

service.login(email, password, new Callback<User>() {         @Override        public void failure(final RetrofitError error) {            android.util.Log.i("example", "Error, body: " + error.getBody().toString());        }        @Override        public void success(User user, Response response) {            // Do something with the User object returned        }    });

Where User is a POJO like

public class User {    private String name;    private String email;    // ... etc.}

and the returned JSON has fields that match the User class:

{  "name": "Bob User",  "email": "bob@example.com",  ...}

If you need custom parsing, the place for that is when setting the REST adapter's converter with .setConverter(Converter converter):

The converter used for serialization and deserialization of objects.


Seem Retrofit have problem with @POST and @FormUrlEncoded. It works well if we do synchronous but failed if asynchronous.

If @mike problem is deserialization object, User class should be

public class User {     @SerializedName("name")     String name;     @SerializedName("email")     String email;}

Interface class

@FormUrlEncoded@POST("/login")void login(@Field("username") String username, @Field("password") String password, Callback<User> callback);

Or

@FormUrlEncoded@POST("/login")void login(@Field("username") String username, @Field("password") String password, Callback<UserResponse> callback);

Where

public class UserResponse {@SerializedName("email")String email;@SerializedName("name")String name;}