问题
I am trying to consume a GET API that expects in its query params list an array of strings.
I am using Retrofit for the task.
In the API interface, I have the following defined:
@GET("user/explore")
Observable<User> fetchUsers(@Query("who") String who,
@Query("category") ArrayList<String> categories);
I am using Timber for logging and in the console, I see the request is made like the following:
http://192.168.2.208:3000/api/v1/user/explore?who=SOME_USER&category=SOME_CATEGORY
The expected request should be made like the following:
http://192.168.2.208:3000/api/v1/user/explore?who=SOME_USER&category=[SOME_CATEGORY,SOME_CATEGORY1,SOME_CATEGORY2]
Why is retrofit behaving this way event though categories are of type string arraylist?
回答1:
ArrayList<String> carArrList = new ArrayList<>();
carArrList.add("a");
carArrList.add("b");
carArrList.add("c");
String[] catArr = (String[]) carArrList.toArray(new String[carArrList.size()]);
String catStr = Arrays.toString(catArr);
catStr = catStr.replaceAll(" ", "");
Log.e("catStr", catStr);
Call<User> call = apiService.fetchUsers(catStr);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
}
@Override
public void onFailure(Call<User> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
@GET("list/")
Call<User> fetchUsers(@Query("category") String categories);
final request generated
list/?category=[a,b,c]
来源:https://stackoverflow.com/questions/44887212/android-retrofit-get-query-arraylist