Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 636
intellignt_idiot Avatar asked Jan 16 '16 11:01

intellignt_idiot


People also ask

How do I use OkHttp on Android?

OkHttp Query Parameters ExampleBuilder urlBuilder = HttpUrl. parse("https://httpbin.org/get).newBuilder(); urlBuilder. addQueryParameter("website", "www.journaldev.com"); urlBuilder. addQueryParameter("tutorials", "android"); String url = urlBuilder.

What is Okhttpclient in Java?

OkHttp is an efficient HTTP & HTTP/2 client for Android and Java applications. It comes with advanced features, such as connection pooling (if HTTP/2 isn't available), transparent GZIP compression, and response caching, to avoid the network completely for repeated requests.

What is the underlying library of OkHttp?

Beginning with Mobile SDK 4.2, the Android REST request system uses OkHttp (v3. 2.0), an open-source external library from Square Open Source, as its underlying architecture. This library replaces the Google Volley library from past releases.


3 Answers

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(); 
like image 141
fahrulazmi Avatar answered Sep 30 '22 05:09

fahrulazmi


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();
like image 44
Nick B Avatar answered Sep 30 '22 03:09

Nick B


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();
}
like image 39
Kasim Rangwala Avatar answered Sep 30 '22 03:09

Kasim Rangwala