[英]Add an array as request parameter with Retrofit 2
我正在尋找使用 retrofit 2 在GET請求中添加 int 數組(例如 [0,1,3,5])作為參數的方法。然后,生成的 url 應該是這樣的: Z80791B3AE7002CB88F8Z2://6serviceDFAFAServer ?array=[0,1,3,5]
這個怎么做?
只需將其添加為查詢參數
@GET("http://server/service")
Observable<Void> getSomething(@Query("array") List<Integer> array);
您還可以使用 int[] 或 Integer... 作為最后一個參數;
您需要使用數組語法命名您的查詢參數,如下所示:
@GET("http://server/service")
Observable<Void> getSomething(@Query("array[]") List<Integer> array);
語法本身會因所使用的后端技術而異,但不包括括號“[]”通常會被解釋為單個值。
例如,使用array=1&array=2
通常會被后端解釋為僅array=1
或array=2
而不是array=[1,2]
。
我終於通過使用 Arrays.toString(int []) 方法並通過刪除此結果中的空格來建立解決方案,因為 Arrays.toString 返回“[0, 1, 3, 5]”。 我的請求方法看起來像這樣
@GET("http://server/service")
Observable<Void> getSomething(@Query("array") String array);
我遇到了類似的問題,必須做一些事情才能達到可接受的形式(如問題中所問)。
將 ArrayList 轉換為 String
arrayList.toString().replace(" ", "")
在 RetroFit 方法中,我將接受上述 ArrayList 的 Query 參數更改為如下:
@Query(value = "cities", encoded = true)
這確保括號和逗號不是 URL 編碼的。
使用toString
對我不起作用。 相反, TextUtils.join(",", ids)
可以解決問題。
不要忘記用encoded = true
標記Query
。
嗯,這對我有用
第1步 :
在StateServce.kt
@GET("states/v1")
fun getStatesByCoordinates(@Query("coordinates", encoded = true) coordinates: String) : Call<ApiResponse<List<State>>>
第2步
從存儲庫調用時
val mCoordinate : List<Double> = [22.333, 22.22]
mStateService?.getStatesByCoordinates(mCoordinate.toString().replace(" ", ""))!!
使用 Iterable 封裝整數列表,或者使用二維整數數組。
如何定義:
public interface ServerService { @GET("service") Call<Result> method1(@Query("array") Iterable<List<Integer>> array); @GET("service") Call<Result> method2(@Query("array") Integer[][] array); }
如何使用:
Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://server/") .addConverterFactory(GsonConverterFactory.create()) .build(); ServerService service = retrofit.create(ServerService.class); // Use the first method. List<Integer> data1 = Arrays.asList(0,1,3,5); Iterable array1 = Arrays.asList(data1); Call<Result> method1Call = service.method1(array1); // Use the second method. Integer[] data2 = new Integer[]{0,1,3,5}; Integer[][] array2 = new Integer[][]{data2}; Call<Result> method2Call = service.method2(array2); // Execute enqueue() or execute() of method1Call or method2Call.
之所以能解決問題,請參考Retrofit2的代碼ParameterHandler.java 。
您可以傳遞如下值
在存儲庫中
getApiResponse(arrayOf(0,1,3,5).contentToString())` 在 Kotlin 中。
@GET("http://server/service")
suspend fun getApiResponse(@Query("array") array: String): Response
它會起作用的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.