Dynamically add params in HTTP request in Retrofit

Updated 8 June 2018


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.

Using Retrofit library to make Http Requests

RxAndroid: From begining to some use cases

Changes needed in the request declaration

Check the below provided code segment. This is how we use to declare the request using retrofit.

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.

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.

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.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*

Be the first to comment.

Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home