Add query parameter to Retrofit get in Android Studio

Add query parameter to Retrofit get in Android Studio

To add query parameters to a Retrofit GET request in Android, you can use annotations in your service interface. Here's how to do it:

Step-by-Step Guide

  1. Add Retrofit Dependency: Make sure you have the Retrofit dependency in your build.gradle file:

    implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' // For JSON parsing 
  2. Create the API Interface: Define your API interface with a GET method that includes query parameters.

    import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; public interface ApiService { @GET("endpoint") Call<YourResponseType> getData( @Query("param1") String param1, @Query("param2") int param2 ); } 
  3. Create the Retrofit Instance: Set up your Retrofit instance in your application or wherever you need to make the network call.

    import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class ApiClient { private static final String BASE_URL = "https://api.example.com/"; private static Retrofit retrofit = null; public static Retrofit getClient() { if (retrofit == null) { retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } } 
  4. Make the API Call: Use the created ApiService to make the network request.

    import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class YourActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ApiService apiService = ApiClient.getClient().create(ApiService.class); Call<YourResponseType> call = apiService.getData("value1", 123); call.enqueue(new Callback<YourResponseType>() { @Override public void onResponse(Call<YourResponseType> call, Response<YourResponseType> response) { if (response.isSuccessful()) { // Handle the response YourResponseType data = response.body(); // Do something with the data } } @Override public void onFailure(Call<YourResponseType> call, Throwable t) { // Handle failure } }); } } 

Explanation:

  • @GET Annotation: Defines the endpoint for the GET request.
  • @Query Annotation: Indicates the parameters to be added to the URL as query parameters.
  • Call Enqueue: Executes the call asynchronously, handling responses in onResponse and onFailure methods.

Note:

  • Replace "endpoint" with your actual endpoint and YourResponseType with the model class that represents the expected response.
  • Ensure to handle exceptions and error responses appropriately in production code.

Examples

  1. How to add a single query parameter to a Retrofit GET request?

    • Description: You can define a method in your Retrofit interface with a @Query annotation to specify the query parameter.
    • Code:
      public interface ApiService { @GET("endpoint") Call<ResponseType> getData(@Query("param") String param); } 
  2. How to add multiple query parameters to a Retrofit GET request?

    • Description: Use multiple @Query annotations in the method signature to add multiple parameters.
    • Code:
      public interface ApiService { @GET("endpoint") Call<ResponseType> getData(@Query("param1") String param1, @Query("param2") String param2); } 
  3. How to make optional query parameters in Retrofit GET?

    • Description: You can use @Query and check for null values to make parameters optional.
    • Code:
      public interface ApiService { @GET("endpoint") Call<ResponseType> getData(@Query("param") String param, @Query("optionalParam") String optionalParam); } 
  4. How to set default values for query parameters in Retrofit?

    • Description: You can set default values by using method overloading or specifying default values in the method signature.
    • Code:
      public interface ApiService { @GET("endpoint") Call<ResponseType> getData(@Query("param") String param, @Query("optionalParam") String optionalParam = "default"); } 
  5. How to handle list parameters in Retrofit GET requests?

    • Description: You can send a list of values as a comma-separated string using the @Query annotation.
    • Code:
      public interface ApiService { @GET("endpoint") Call<ResponseType> getData(@Query("ids") List<Integer> ids); } 
  6. How to encode query parameters in Retrofit?

    • Description: Retrofit automatically handles encoding, but you can ensure special characters are encoded using @Query.
    • Code:
      public interface ApiService { @GET("endpoint") Call<ResponseType> getData(@Query("search") String search); // Special characters are encoded automatically } 
  7. How to use dynamic query parameters in Retrofit?

    • Description: Pass dynamic values to the @Query parameter when calling the API method.
    • Code:
      ApiService apiService = retrofit.create(ApiService.class); Call<ResponseType> call = apiService.getData("dynamicValue"); 
  8. How to add query parameters conditionally in Retrofit?

    • Description: Create different API method overloads to handle conditions.
    • Code:
      public interface ApiService { @GET("endpoint") Call<ResponseType> getData(@Query("param") String param); @GET("endpoint") Call<ResponseType> getDataWithOptional(@Query("param") String param, @Query("optional") String optional); } 
  9. How to log query parameters in Retrofit requests?

    • Description: Use an OkHttp interceptor to log requests, including query parameters.
    • Code:
      OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) .build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.example.com/") .client(client) .build(); 
  10. How to test Retrofit GET requests with query parameters?

    • Description: Use a testing library like Mockito to mock the API service and test your requests with different query parameters.
    • Code:
      @Test public void testGetData() { ApiService apiService = Mockito.mock(ApiService.class); Call<ResponseType> call = apiService.getData("test"); // Add assertions here } 

More Tags

git-revert angularjs-service media sharepoint-clientobject repeat sql-like laravel-5.3 matplotlib pong apk

More Programming Questions

More Stoichiometry Calculators

More Mortgage and Real Estate Calculators

More Chemical thermodynamics Calculators

More Math Calculators