FelixHJ FelixHJ - 1 month ago 4
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()
.scheme("https")
.host("example.com")
.addEncodedPathSegment("path")
.addQueryParameter("name","John Doe")
.build();


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

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

Answer

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

HttpUrl.Builder httpUrlBuilder = new HttpUrl.Builder()
                .scheme("https")
                .host("example.com");

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()
                .url(httpUrl)
                .get()
                .build();
Comments