Add an array as request parameter with Retrofit 2

杀马特。学长 韩版系。学妹 提交于 2019-12-01 03:29:57

Just add it as a query param

@GET("http://server/service")
Observable<Void> getSomething(@Query("array") List<Integer> array);

You can also use int[], or Integer... as a last param;

I have finally founded a solution by using Arrays.toString(int []) method and by removing spaces in this result because Arrays.toString return "[0, 1, 3, 5]". And my request method looks like this

@GET("http://server/service")
Observable<Void> getSomething(@Query("array") String array);

I faced a similar problem and had to do a couple of things to reach the acceptable form (as asked in the question).

  1. Converted an ArrayList to String

    arrayList.toString().replace(" ", "")
    
  2. In RetroFit method, I changed the Query param which accepts the ArrayList above to as follows:

    @Query(value = "cities", encoded = true)
    

This ensures that the brackets and commas are not URL encoded.

Using toString didn't work for me. Instead, TextUtils.join(",", ids) does the trick.

Don't forget to mark the Query with encoded = true.

You need to name your query param with an array syntax like so:

@GET("http://server/service")
Observable<Void> getSomething(@Query("array[]") List<Integer> array);

The syntax itself will vary by the backend technology being used, however not including the brackets "[]" will normally be interpreted as a single value.

For example, using array=1&array=2 will generally be interpreted by backends as only array=1 or array=2 instead of array=[1,2].

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