FelixHJ FelixHJ - 1 year ago 86
Java Question

Iterate over parameters for request

I have a

Map<String,String> params = .....

with the key+value for the parameters for a GET request.

Building a HttpUrl looks something like this:

HttpUrl httpUrl = new HttpUrl.Builder()
.addQueryParameter("name","John Doe")

how do I add the (unknown beforehand and/or variable) parameters in
to the HttpUrl, i.e. iterate over the values in
and call
for each key+value?

EDIT sorry I was not specific enough: I need to know if I can call
repeatedly inside a loop somehow, not how to iterate over a Map.

Answer Source

For it to work one must start with a HttpUrl.builder:

HttpUrl.Builder httpUrlBuilder = new HttpUrl.Builder()

followed by adding the parameters:

for (Map.Entry<String,String> entry: params.entrySet()) {
            httpUrlBuilder.addQueryParameter(entry.getKey(), entry.getValue());

and finally building the request:

HttpUrl httpUrl = httpUrlBuilder.build();
Request request = new Request.Builder()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download