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

五迷三道 提交于 2019-11-30 11:08:43
fahrulazmi

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();

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();

Here's my version

/**
 * <strong>Uses:</strong><br/>
 * <p>
 * {@code
 * List<Pair<String, String>> pairs = new ArrayList<>();}
 * <br/>
 * {@code pairs.add(new Pair<>("key1", "value1"));}<br/>
 * {@code pairs.add(new Pair<>("key2", "value2"));}<br/>
 * {@code pairs.add(new Pair<>("key3", "value3"));}<br/>
 * <br/>
 * {@code postToServer("http://www.example.com/", pairs);}<br/>
 * </p>
 *
 * @param url
 * @param pairs List of support.V4 Pair
 * @return response from server in String format
 * @throws Exception
 */
public String postToServer(String url, List<Pair<String, String>> pairs) throws Exception {
    okhttp3.OkHttpClient client = new okhttp3.OkHttpClient();
    okhttp3.Request.Builder builder = new okhttp3.Request.Builder().url(url);

    if (pairs != null) {
        okhttp3.FormBody.Builder postData = new okhttp3.FormBody.Builder();
        for (Pair<String, String> pair : pairs) {
            postData.add(pair.first, pair.second);
        }
        builder.post(postData.build());
    }
    okhttp3.Request request = builder.build();
    okhttp3.Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
        throw new IOException(response.message() + " " + response.toString());
    }
    return response.body().string();
}

I am not sure but you can try something like that :

RequestBody formBody = new FormBody.Builder();
for(...;...;...) {
   formBody.add(...)
}
formBody.build();

the rest of your code seems good. Hope it will work :) !

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!