Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add post parameters in loop - OkHTTP

I'm using OkHTTP for making a post request to my server. I know I can build a request like this:

RequestBody formBody = new FormEncodingBuilder()
            .add("param1", param1)
            .build();
    Request request = new Request.Builder()
            .url(url)
            .post(formBody)
            .build();

So what I want to do is to add the parameters dynamically. E.g:

RequestBody formBody = new FormEncodingBuilder()
    for (ParamsArray m : requestParams) {
        formBody.add("param1", requestParams.value);
    }

But there's no function add for a RequestBody and I don't know if it is possible to convert a FormEncodingBuilder to a RequestBody.

Thank you!

like image 459
jossiwolf Avatar asked Jun 22 '26 09:06

jossiwolf


1 Answers

A FormEncodingBuilder will turn into a RequestBody when you build it. Looking at the documentation, something like this ought to work.

FormEncodingBuilder formBodyBuilder = new FormEncodingBuilder()
for (ParamsArray m : requestParams) {
    formBodyBuilder.add("param1", requestParams.value);
}
RequestBody body = formBodyBuilder.build()

The documentation is available here: https://square.github.io/okhttp/2.x/okhttp/com/squareup/okhttp/FormEncodingBuilder.html

like image 191
daentech Avatar answered Jun 26 '26 20:06

daentech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!