0

我搜索了一下,但找不到“Armeria API”来优雅地做到这一点。我对 Netty 很熟悉,所以目前我正在使用QueryStringEncoder. 有一个更好的方法吗 ?在这里,我有一个动态Map参数,我需要以编程方式构建 HTTP 客户端。ArmeriaWebClientRequestHeadersbuilder 提供了添加标题和路径的方法,但不提供查询字符串参数。

    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);
4

1 回答 1

2

ArmeriaQueryParams用于构建或解析查询字符串:

// 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()

您可能还会发现Cookie有用。

于 2020-08-31T03:32:09.077 回答