Sending list of objects in form-urlencoded request using Retrofit2

1.4k Views Asked by At

This is my postman request:

enter image description here

I'm going to send a POST request using Retrofit2, Gson and RxJava2. This is my request:

@FormUrlEncoded
@POST("Student") // I'm sure the address and name are correct
Completable Student(@Field("firstName") String firstName,
                    @Field("lastName") String lastName,
                    @Field("exam[]") List<Exam> exams
);

And this is Exam model created using POJO Generator:

public class Exam {

@SerializedName("score")
private int score;

@SerializedName("field")
private String field;

public void setScore(int score){
    this.score = score;
}

public int getScore(){
    return score;
}

public void setField(String field){
    this.field = field;
}

public String getField(){
    return field;
}

@Override
public String toString(){
    return 
        "Exam{" + 
        "score = '" + score + '\'' + 
        ",field = '" + field + '\'' + 
        "}";
    }
}

Postman sends the request correctly and receives the response code 204 but my Retrofit request cannot send request correctly. How can I send list of objects in x-www-form-urlencoded request using Retrofit version 2 and RxJava version 2?

2

There are 2 best solutions below

2
On BEST ANSWER

May be you can try with this:

@FormUrlEncoded
@POST("Student") // I'm sure the address and name are correct
Completable Student(@Field("firstName") String firstName,
                    @Field("lastName") String lastName,
                    @FieldMap Map<String, String>
);

  *****************************
// how to use the map
Map<String, String> params = new HashMap<>();
params.put("exam[0][field]","Math");
params.put("exam[0][score]","90");
params.put("exam[1][field]", "Physics");
params.put("exam[1][score]", "99");
1
On

If the Postman request works then this would be the Retrofit equivalent:

@FormUrlEncoded
@POST("Student")
Completable Student(@Field("firstName") String firstName,
                    @Field("lastName") String lastName,
                    @FieldMap Map<String, String> fieldMap
);

and then run a loop to fill in the details

public void sendRequest(List<Exam> exams) {
    Map<String, String> map = new HashMap<>();
    for (int i = 0; i < exams.size(); i++) {
        map.put("exam[" + i + "].field", exams.get(i).getField());
        map.put("exam[" + i + "].score", String.valueOf(exams.get(i).getScore()));
    }
    yourApiService.Student(firstName, lastName, map); // enqueue or execute whatever
}

This is more of a simpler approach you could also look into custom a JsonSerializer with Gson.