gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:57:43 26 4
gpt4 key购买 nike

我需要使用 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 的参数。我还尝试过使用数组以及带字符串的列表。同样的问题。一切都直接出现在一个条目中。

那我该怎么办呢?

最佳答案

作为对象发送

这是您的 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
};

关于android - 如何使用 Retrofit 发送数组/列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37698715/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com