【问题标题】:Get http response code and all available body获取 http 响应代码和所有可用的正文
【发布时间】:2019-11-04 05:04:39
【问题描述】:

我想实现 WebFlux 示例客户端,它可以使用 http 参数发出请求并获取响应正文和 http 响应代码。我试过这个:

public ClientResponse execute(NotificationMessage nm)
Mono<String> transactionMono = Mono.just(convertedString);
        return client.post().uri(builder -> builder.build())
                .header(HttpHeaders.USER_AGENT, "agent")
                .body(transactionMono, String.class).exchange().block();
    }

    private static String convert(Map<String, String> map) throws UnsupportedEncodingException {
        String result = map.entrySet().stream().map(e -> encode(e.getKey()) + "=" + encode(e.getValue()))
                .collect(Collectors.joining("&"));
        return result;
    }

    private static String encode(String s) {
        try {
            return URLEncoder.encode(s, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e);
        }
    }

您能否在.exchange() 之后给我一些建议,如何获取 http 状态代码和所有可用的正文。

【问题讨论】:

    标签: java spring spring-boot spring-mvc spring-webflux


    【解决方案1】:

    从 exchange 返回的 ClientResponse 对象中,您可以使用 response.statusCode() 获取状态并使用 response.bodyToMono() 或 bodyToFlux() 获取实际正文。您应该避免在响应式编程中使用 .block() 并使用 .subscribe() 或 .flatMap() 或其他运算符从 Mono 或 Flux 对象获取数据。 Read more 关于响应式编程和 Project reactor(由 spring webflux 使用)在这里。

    例如:

    public Mono<Data> execute(NotificationMessage nm)
        return client.post().uri(builder -> builder.build())
                    .header(HttpHeaders.USER_AGENT, "agent")
                    .body(transactionMono, String.class).exchange()
                    .flatMap(response -> {
                            HttpStatus code = response.statusCode();
                            Data data = response.bodyToMono(Data.class);
                            return data;
                    });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-30
      • 1970-01-01
      • 1970-01-01
      • 2018-02-27
      • 1970-01-01
      • 2012-04-01
      • 2013-03-15
      • 1970-01-01
      相关资源
      最近更新 更多