How to send Arrays / Lists with Retrofit

一曲冷凌霜 提交于 2019-12-18 03:17:09

问题


I need to send a list / an array of Integer values with Retrofit to the server (via POST) I do it this way:

@FormUrlEncoded
@POST("/profile/searchProfile")
Call<ResponseBody> postSearchProfile(
        @Field("age") List<Integer> age
};

and send it like this:

ArrayList<Integer> ages = new ArrayList<>();
        ages.add(20);
        ages.add(30);

ISearchProfilePost iSearchProfile = gsonServerAPIRetrofit.create(ISearchProfilePost.class);
        Call<ResponseBody> call = iSearchProfile.postSearchProfile(
                ages
        );

The problem is, the values reach the server not comma separated. So the values there are like age: 2030 instead of age: 20, 30.

I was reading (e.g. here https://stackoverflow.com/a/37254442/1565635) that some had success by writing the parameter with [] like an array but that leads only to parameters called age[] : 2030. I also tried using Arrays as well as Lists with Strings. Same problem. Everything comes directly in one entry.

So what can I do?


回答1:


To send as an Object

This is your ISearchProfilePost.class

@FormUrlEncoded
@POST("/profile/searchProfile")
Call<ResponseBody> postSearchProfile(@Body ArrayListAge ages);

Here you will enter the post data in pojo class

public class ArrayListAge{
    @SerializedName("age")
    @Expose
    private ArrayList<String> ages;
    public ArrayListAge(ArrayList<String> ages) {
        this.ages=ages;
    }
}

Your retrofit call class

ArrayList<Integer> ages = new ArrayList<>();
        ages.add(20);
        ages.add(30);

ArrayListAge arrayListAge = new ArrayListAge(ages);
ISearchProfilePost iSearchProfile = gsonServerAPIRetrofit.create(ISearchProfilePost.class);
Call<ResponseBody> call = iSearchProfile.postSearchProfile(arrayListAge);

To send as an Array List check this link https://github.com/square/retrofit/issues/1064

You forget to add age[]

@FormUrlEncoded
@POST("/profile/searchProfile")
Call<ResponseBody> postSearchProfile(
    @Field("age[]") List<Integer> age
};



回答2:


Retrofit can do this now at least I tested with this -> implementation 'com.squareup.retrofit2:retrofit:2.1.0'

For example

@FormUrlEncoded
@POST("index.php?action=item")
Call<Reply> updateStartManyItem(@Header("Authorization") String auth_token, @Field("items[]") List<Integer> items, @Field("method") String method);

This is the piece we are looking at.

@Field("items[]") List<Integer> items


来源:https://stackoverflow.com/questions/37698715/how-to-send-arrays-lists-with-retrofit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!