Armeria HTTP Client - how to add query string parameters

598 views Asked by At

I searched for a bit but couldn't find an "Armeria API" to do this elegantly. I'm familiar with Netty so for the time being I'm using QueryStringEncoder. Is there a better way to do this ? Here I have a dynamic Map of params and I need to build the HTTP client programmatically. The Armeria WebClient and RequestHeaders builders provide ways to add headers and path, but not query string parameters.

    HttpMethod httpMethod = HttpMethod.valueOf('GET');
    String url = 'http://example.com'
    String path = '/foo';
    if (params != null) {
        QueryStringEncoder qse = new QueryStringEncoder(url + path);
        params.forEach((k, v) -> {
            if (v != null) {
                v.forEach(s -> qse.addParam(k, s));
            }
        });            
        try {
            URI uri = qse.toUri();
            path = path + "?" + uri.getRawQuery();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    WebClient webClient = WebClient.builder(url).decorator(new HttpClientLogger()).build();
    RequestHeadersBuilder rhb = RequestHeaders.builder(httpMethod, path);
1

There are 1 answers

7
trustin On BEST ANSWER

Armeria has QueryParams for building or parsing a query string:

// You don't really need a Map to build a QueryParams.
// See QueryParams.of() or QueryParamsBuilder.add() for more information.
Map<String, String> paramMap = ...;
QueryParams params =
    QueryParams.builder()
               .add(paramMap)
               .build();

WebClient client =
    WebClient.builder("http://example.com")
             .decorator(...)
             .build();

AggregatedHttpResponse res =
    client.get("/foo?" + params.toQueryString()).aggregate().join()

You might also find Cookie useful.