Q:

How to send post parameters dynamically (or in loop) in OKHTTP 3.x in android?

I am using OKHTTP 3.x version. I want to post multiple  parameters and would like to add the params in a loop.
I know that in version 2.x , I can use FormEncodingBuilder and add params to it in loop and then from it create a request body.
But In 3.x , the class has been removed.
Here is my current code :
RequestBody formBody = new FormBody.Builder()
            .add("Param1", value1)
            .add("Param2", value2)
            .build();
Request request = new Request.Builder()
            .url("url")
            .post(formBody)
            .build();

Now I want to add 5 params but in a loop i.e create request body by building formbody in a loop.
Like I wrote above, I know how to do it in OKHTTP version 2.x but I am using version  3.x.
Any help or guidance is appreciated.
Thanks in Advance

A:

Here's how I do it:
FormBody.Builder formBuilder = new FormBody.Builder()
        .add("key", "123");

// dynamically add more parameter like this:
formBuilder.add("phone", "000000");

RequestBody formBody = formBuilder.build();

Request request = new Request.Builder()
                .url("https://aaa.com")
                .post(formBody)
                .build();

A:

Imports
import okhttp3.OkHttpClient;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;

Code:
// HashMap with Params
HashMap<String, String> params = new HashMap<>();
params.put( "Param1", "A" );
params.put( "Param2", "B" );

// Initialize Builder (not RequestBody)
FormBody.Builder builder = new FormBody.Builder();

// Add Params to Builder
for ( Map.Entry<String, String> entry : params.entrySet() ) {
    builder.add( entry.getKey(), entry.getValue() );
}

// Create RequestBody
RequestBody formBody = builder.build();

// Create Request (same)
Request request = new Request.Builder()
        .url( "url" )
        .post( formBody )
        .build();

