【问题标题】:How to send Arrays / Lists with Retrofit如何使用 Retrofit 发送数组/列表
【发布时间】:2016-06-08 09:36:14
【问题描述】:

我需要通过 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

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

那我该怎么办?

【问题讨论】:

标签: android http-post retrofit


【解决方案1】:

作为对象发送

这是你的 ISearchProfilePost.class

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

这里输入pojo类的post数据

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

你的改造调用类

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

要作为数组列表发送,请查看此链接https://github.com/square/retrofit/issues/1064

您忘记添加age[]

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

【讨论】:

  • 好吧,但这会将我的对象作为主体发送,而不是作为其他字段中的一个“数组”发送。不是吗?
【解决方案2】:

改造现在可以做到这一点,至少我用这个测试过 -> 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

【讨论】:

  • 在 2.6 已经发布的情况下使用“现在”版本 2.1 是否有特定原因?或者这应该意味着“从 2.1 开始工作”?
  • 正是我对其进行的测试...编辑了答案以包含此详细信息。
猜你喜欢
  • 2015-06-23
  • 1970-01-01
  • 1970-01-01
  • 2017-02-02
  • 1970-01-01
  • 2017-06-08
  • 1970-01-01
  • 2018-02-20
  • 1970-01-01
相关资源
最近更新 更多