Add an array as request parameter with Retrofit 2

后端 未结 7 726
故里飘歌
故里飘歌 2020-12-10 11:04

I\'m looking for way to add an int array (e.g [0,1,3,5]) as parameter in a GET request with retrofit 2. Then, the generated url should be like this : http:/

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 11:54

    Use Iterable to encapsulate the integer list, or use a two-dimensional integer array.

    • How to define:

      public interface ServerService {
          @GET("service")
          Call method1(@Query("array") Iterable> array);
      
          @GET("service")
          Call method2(@Query("array") Integer[][] array);
      }
      
    • How to use:

      Retrofit retrofit = new Retrofit.Builder()
          .baseUrl("http://server/")
          .addConverterFactory(GsonConverterFactory.create())
          .build();
      ServerService service = retrofit.create(ServerService.class);
      
      // Use the first method.
      List data1 = Arrays.asList(0,1,3,5);
      Iterable array1 = Arrays.asList(data1);
      Call method1Call = service.method1(array1);
      
      // Use the second method.
      Integer[] data2 = new Integer[]{0,1,3,5};
      Integer[][] array2 = new Integer[][]{data2};
      Call method2Call = service.method2(array2);
      
      // Execute enqueue() or execute() of method1Call or method2Call.
      

    Please refer to the code ParameterHandler.java of Retrofit2 for the reason why the way can solve the problem.

提交回复
热议问题