没有重复参数名称的动态参数列表

dynamic list of parameters without having repeated parameter name

我休息api喜欢:

http://MY_SERVER/api/story?feed_ids=1,2,3&page=1

这里我应该提供动态 feed_ids列表,用逗号分隔, 为此,我写了我的休息服务:

@GET("/story")
void getStory( @Query("feed_ids") List<Integer> feed_items, @Query("page") int  page,Callback<StoryCollection> callback);

和:

private List<Integer> items = Arrays.asList(1, 2, 3); // items is a list of  feed ids subscribed by user (retrieved from app db). initialization is done here just for testing 

public void getLatestStoryCollection(int page ,Callback<StoryCollection> callback) {
            newsService.getStory(items,  page ,callback);
}

我的代码运行正常,但改装发送请求 url 如:

http://MY_SERVER/api/story?feed_ids=1&feed_ids=2&feed_ids=3&page=1 

有没有办法像feed_ids=1,2,3一样发送这样的动态参数列表而无需重复参数名称?

没有办法在改造中做到这一点,但你可以自己很容易地做到这一点。由于您使用的是 android,因此您可以使用 TextUtils.join() 将任何列表转换为字符串。然后将该字符串作为查询参数而不是列表传递给。首先,更新您的界面以使用 String 而不是 List.

@GET("/story")
void getStory( @Query("feed_ids") String feed_items, @Query("page") int page, Callback<StoryCollection> callback);

然后当您调用 getStory 方法时,首先将项目传递给 join --

String items = TextUtils.join(",", Arrays.asList(1, 2, 3));
newsService.getStory(items, page, callback);

您可以创建一个覆盖 toString() 的自定义 class 以将它们格式化为逗号分隔列表。类似于:

class FeedIdCollection extends List<Integer> {
    public FeedIdCollection(int... ids) {
        super(Arrays.asList(ids));
    }

    @Override
    public String toString() {
        return TextUtils.join(",", this);
    }
}

然后进行声明:

@GET("/story")
void getStory( @Query("feed_ids") FeedIdCollection feed_items, @Query("page") int page, Callback<StoryCollection> callback);