如何使用 Retrofit 发送数组/列表

How to send Arrays / Lists with Retrofit

我需要将带有 Retrofit 的整数值列表/数组发送到服务器(通过 POST) 我是这样做的:

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

然后这样发送:

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

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

问题是,到达服务器的值不是逗号分隔的。所以那里的值就像 age: 2030 而不是 age: 20, 30.

我读到(例如这里 )有些人通过像数组一样用 [] 编写参数取得了成功,但这只会导致名为 age[] 的参数:2030。 我还尝试过使用数组以及带字符串的列表。同样的问题。一切都直接在一个条目中。

那我该怎么办?

作为对象发送

这是你的ISearchProfilePost.class

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

这里要在pojo中输入post数据class

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

你的改装电话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);

要作为数组列表发送,请选中此 link https://github.com/square/retrofit/issues/1064

您忘记添加age[]

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

Retrofit 现在可以做到这一点至少我用这个测试过 -> implementation 'com.squareup.retrofit2:retrofit:2.1.0'

例如

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

这就是我们正在看的作品。

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