Search code examples
javaandroidretrofit2rx-java2x-www-form-urlencoded

Sending list of objects in form-urlencoded request using Retrofit2


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?


Solution

  • 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");