In the previous blogs related to Retrofit library, we have discussed several points like how to do things using it and the issues that you may face and how to resolve them. If you have not covered those topics then I suggest that you should because we will be directly focusing on dynamically adding the params in a Retrofit request. Some of the blog links are mentioned below and I am sure you can definitely find the rest of the blogs.
Changes needed in the request declaration
Check the below provided code segment. This is how we use to declare the request using retrofit.
1 2 3 4 5 6 7 8 9 10 |
@FormUrlEncoded @POST(your_url_without_base_url) Call<your_response_data_model> your_request_name( @Header("your_key_name") String your_variable_name , @Header("your_key_name") String your_variable_name , @Header("your_key_name") String your_variable_name , @Field("your_key_name") int your_variable_name , @Field("your_key_name") int your_variable_name ); |
these are all static fields and you cannot change their names or the type. The problem arises when you have a key whose name is dynamic and you cannot add the field just like the above method. In this case, all you need to do is add another param with annotation FieldPath. The below provided code segment shows how you can achieve this.
1 2 3 4 5 6 7 8 9 10 11 |
@FormUrlEncoded @POST(your_url_without_base_url) Call<your_response_data_model> your_request_name( @Header("your_key_name") String your_variable_name , @Header("your_key_name") String your_variable_name , @Header("your_key_name") String your_variable_name , @Field("your_key_name") int your_variable_name , @Field("your_key_name") int your_variable_name , @FieldMap Map<String, String> your_variable_name ); |
Now we have added the Map as the param and we put all the dynamic keys and values in this Map. The retrofit will add those Maps as the params in the request.
Changes needed during the request call
During the request call, You need to create a HashMap and add all your dynamic key into it and pass the HashMap to the FieldMap params. The retrofit will automatically add those key values as the params in the request. The below provided code segment is an example of how to call the request with the FieldMap param.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
HashMap<String, RequestBody> dynamicParams = new HashMap<>(); dynamicParams.put("your_dynamic_key", value); dynamicParams.put("your_dynamic_key", value); dynamicParams.put("your_dynamic_key", value); Call<your_response_data_model> call = RetrofitClient.getClient().create(your_class_where_request_is_created.class).your_request_name( your_param_1 , your_param_2 , your_param_3 , your_param_4 , your_param_5 , dynamicParams ); call.enqueue(your_callback_method_name); |
That’s all you need. If you are creating a multipart request then you will have to use PartMap and also for adding any Query parameter you can you QueryMap.
Thank you very much. This is Vedesh Kumar signing off.